-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMinimumDistanceBetweenBSTNodes.java
More file actions
39 lines (33 loc) · 989 Bytes
/
MinimumDistanceBetweenBSTNodes.java
File metadata and controls
39 lines (33 loc) · 989 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package binary_search_tree;
import java.util.Deque;
import java.util.LinkedList;
/**
* Description: https://leetcode.com/problems/minimum-distance-between-bst-nodes
* Difficulty: Easy
* Time complexity: O(n)
* Space complexity: O(n)
*/
public class MinimumDistanceBetweenBSTNodes {
public int minDiffInBST(TreeNode root) {
Deque<TreeNode> stack = new LinkedList<>();
int minDiff = Integer.MAX_VALUE;
TreeNode prev = null;
while (!stack.isEmpty() || root != null) {
if (root != null) {
stack.push(root);
root = root.left;
} else {
root = stack.pop();
if (prev != null) minDiff = Math.min(minDiff, Math.abs(root.val - prev.val));
prev = root;
root = root.right;
}
}
return minDiff;
}
private static class TreeNode {
int val;
TreeNode left;
TreeNode right;
}
}