首页 > 代码库 > 530. 平衡二叉树中,相邻节点的最小差 Minimum Absolute Difference in BST

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

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. }




null


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