码迷,mamicode.com
首页 > 其他好文 > 详细

530. 平衡二叉树中,相邻节点的最小差 Minimum Absolute Difference in BST

时间:2017-05-19 01:00:11      阅读:351      评论:0      收藏:0      [点我收藏+]

标签:des   flow   nat   nim   overflow   code   最小   with   order   

Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.

Example:

Input:

   1
         3
    /
   2

Output:
1

Explanation:
The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).

Note: There are at least two nodes in this BST.


  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * public int val;
  5. * public TreeNode left;
  6. * public TreeNode right;
  7. * public TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public int GetMinimumDifference(TreeNode root) {
  12. if (root == null) {
  13. return 0;
  14. }
  15. int min = Int32.MaxValue;
  16. Stack<TreeNode> stack = new Stack<TreeNode>();
  17. TreeNode current = root;
  18. while (current != null) {
  19. stack.Push(current);
  20. current = current.left;
  21. }
  22. while (stack.Count != 0) {
  23. current = stack.Pop();
  24. if (stack.Count > 0) {
  25. int diff = Math.Abs(stack.Peek().val - current.val);
  26. min = Math.Min(diff,min);
  27. }
  28. TreeNode node = current.right;
  29. while (node != null) {
  30. stack.Push(node);
  31. node = node.left;
  32. if (stack.Count > 0) {
  33. int diff = Math.Abs(stack.Peek().val - current.val);
  34. min = Math.Min(diff,min);
  35. }
  36. }
  37. }
  38. return min;
  39. }
  40. }






530. 平衡二叉树中,相邻节点的最小差 Minimum Absolute Difference in BST

标签:des   flow   nat   nim   overflow   code   最小   with   order   

原文地址:http://www.cnblogs.com/xiejunzhao/p/e62939204dc40c6113eff30dfd622f62.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!