Given a Binary Search Tree (BST) with the root noderoot
, return the minimum difference between the values of any two different nodes in the tree.
Example :
Input: root = [4,2,6,1,3,null,null]
Output: 1
Explanation:
Note that root is a TreeNode object, not an array.
The given tree [4,2,6,1,3,null,null] is represented by the following diagram:
4
/ \
2 6
/ \
1 3
while the minimum difference in this tree is 1, it occurs between node 1 and node 2, also between node 3 and node 2.
Note:
- The size of the BST will be between 2 and
100
. - The BST is always valid, each node's value is an integer, and each node's value is different.
这道题可以利用一下BST的性质,最小距离要么是一个树的root和左子树中最大值的差,要么是右子树最小值和root的差,要么来自左右子树的最小距离。可以通过inorder traversal 来解决
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDiffInBST(TreeNode root) {
if(root == null)
return 0;
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode p = root;
while(p != null) {
stack.push(p);
p = p.left;
}
int res = Integer.MAX_VALUE;
Integer last = null;
while(stack.size() > 0) {
TreeNode temp = stack.pop();
if(last == null) {
last = temp.val;
} else {
res = Math.min(res, temp.val - last);
last = temp.val;
}
if(temp.right != null) {
p = temp.right;
while(p != null) {
stack.push(p);
p = p.left;
}
}
}
return res;
}
}