LeetCode 783. Minimum Distance Between BST Nodes
考点 | 难度 |
---|---|
Tree | Easy |
题目
Given the root
of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.
思路
和530题一样。
答案
class Solution {
int min = Integer.MAX_VALUE;
Integer prev = null;
public int minDiffInBST(TreeNode root) {
if (root == null) return min;
minDiffInBST(root.left);
if (prev != null) {
min = Math.min(min, root.val - prev);
}
prev = root.val;
minDiffInBST(root.right);
return min;
}
}