LeetCode 783. Minimum Distance Between BST Nodes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const minDiffInBST = (root) => {
let ans = Number.MAX_SAFE_INTEGER, prev = -1;
const dfs = (root) => {
if (root) {
dfs(root.left);
if (prev != -1)
ans = Math.min(ans, root.val - prev);
prev = root.val;
dfs(root.right);
}
};
dfs(root);
return ans;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const minDiffInBST = (root) => {
let ans = Number.MAX_SAFE_INTEGER, prev = -1;
const stk = [];
while (stk.length > 0 || root) {
while (root) {
stk.push(root);
root = root.left;
}
root = stk.pop();
if (prev != -1)
ans = Math.min(ans, root.val - prev);
prev = root.val;
root = root.right;
}
return ans;
};