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).
BST一般都是中序,不然也没必要出BST的题了啊
左
打印。这里怎么去和别的所有节点、包括之前的取得联系呢?这个地方我觉得挺困难的。
就是prev = root;就行了,具体的迭代不用管
右
TreeNode prev = root; 比较完了再更改
Math.abs(root.val - prev.val)); 而且要用绝对值啊!
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int result = Integer.MAX_VALUE;
TreeNode prev = new TreeNode(0);
public int getMinimumDifference(TreeNode root) {
//cc
if (root == null) {
return 0;
}
getMinimumDifference(root.left);
if (Math.abs(root.val - prev.val) < result) {
result = Math.abs(root.val - prev.val);
}
prev = root;
getMinimumDifference(root.right);
return result;
}
}