Version #1 Recursive in-order traversal
class Solution {
Integer prev;
int min;
public int minDiffInBST(TreeNode root) {
if (root != null) {
min = Integer.MAX_VALUE;
dfs(root);
}
return min == Integer.MAX_VALUE ? -1 : min;
}
// update prev and min, guaranteed node is not null
private void dfs(TreeNode node) {
if (node.left != null) {
dfs(node.left);
}
if (prev != null) {
min = Math.min(min, Math.abs(node.val - prev));
}
prev = node.val;
if (node.right != null) {
dfs(node.right);
}
}
}
No comments:
Post a Comment