Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.
Example 1:
Input: root = [4,2,6,1,3]
Output: 1
Example 2:
Input: root = [1,0,48,null,null,12,49]
Output: 1
Constraints:
The number of nodes in the tree is in the range [2, 100].
0 <= Node.val <= 105
思路:求diff,那么BST的inorder是从小到大的。其实就是一个inorder traverse,披了个外衣。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int minDiffInBST(TreeNode root) {
if(root == null) {
return 0;
}
Stack<TreeNode> stack = new Stack<>();
pushLeft(stack, root);
int res = Integer.MAX_VALUE;
TreeNode pre = null;
while(!stack.isEmpty()) {
TreeNode node = stack.pop();
if(pre != null) {
res = Math.min(res, node.val - pre.val);
}
pre = node;
if(node.right != null) {
pushLeft(stack, node.right);
}
}
return res;
}
public void pushLeft(Stack<TreeNode> stack, TreeNode node) {
while(node != null) {
stack.push(node);
node = node.left;
}
}
}