Description
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example:
Input:
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.
Solution
Inorder Traversal, time O(n), space O(n)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int getMinimumDifference(TreeNode root) {
List<Integer> list = new LinkedList<>();
inorderTraversal(root, list);
int minDiff = Integer.MAX_VALUE;
for (int i = 1; i < list.size(); ++i) {
minDiff = Math.min(minDiff, list.get(i) - list.get(i - 1));
}
return minDiff;
}
public void inorderTraversal(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
inorderTraversal(root.left, list);
list.add(root.val);
inorderTraversal(root.right, list);
}
}
Inorder Traversal, time O(n), space O(1)
可以用辅助的成员变量来记录前一个访问过的节点pre,这样可以省去额外的空间开销。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int minDiff = Integer.MAX_VALUE;
private TreeNode pre = null;
public int getMinimumDifference(TreeNode root) {
inorderTraversal(root);
return minDiff;
}
public void inorderTraversal(TreeNode root) {
if (root == null) {
return;
}
inorderTraversal(root.left);
if (pre != null) {
minDiff = Math.min(minDiff, root.val - pre.val);
}
pre = root;
inorderTraversal(root.right);
}
}