-
Notifications
You must be signed in to change notification settings - Fork 23
/
Minimum Absolute Difference in BST.java
executable file
·77 lines (67 loc) · 1.87 KB
/
Minimum Absolute Difference in BST.java
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
E
tags: BST
BST: inorder-traversal: 先left node(adding to stack till left leav), 再process stack.peek (mid node), 再 add rightNode && dive to rightNode.left leaf
```
/*
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example:
Input:
1
\
3
/
2
Output:
1
Explanation:
The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
Note: There are at least two nodes in this BST.
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
/*
Thoughts:
Given BST, we can in-order traverse the nodes and keep note of the minDiff.
*/
class Solution {
public int getMinimumDifference(TreeNode root) {
if (root == null) {
return 0;
}
int minDiff = Integer.MAX_VALUE;
final Stack<TreeNode> stack = new Stack<>();
TreeNode node = root;
//Initialize: dive deep to left leaf
while (node != null) {
stack.push(node);
node = node.left;
}
node = stack.peek();
TreeNode lastNode = node;
while (!stack.isEmpty()) {
// Mid: take mid, calculate diff based on lastNode
node = stack.pop();
if (node.val != lastNode.val) {
minDiff = Math.min(minDiff, Math.abs(node.val - lastNode.val));
}
lastNode = node;
// Right: stack right node, and attempt to all rightNode.left tll the leaf
if (node.right != null) {
node = node.right;
while (node != null) {
stack.push(node);
node = node.left;
}
}
}
return minDiff;
}
}
```