题目
https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst/
题解
中序遍历法。
本题要求二叉搜索树任意两节点差的绝对值的最小值,而我们知道二叉搜索树有个性质为二叉搜索树中序遍历得到的值序列是递增有序的。
过程中定义了 Record 实例,参考:leetcode 235. 二叉搜索树的最近公共祖先(Java版,树形dp套路)
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;
}
}
public class Solution {
class Record {
int pre;
int ans;
}
public int getMinimumDifference(TreeNode root) {
Record record = new Record();
record.pre = -1;
record.ans = Integer.MAX_VALUE;
dfs(root, record);
return record.ans;
}
public void dfs(TreeNode root, Record record) {
if (root == null) {
return;
}
dfs(root.left, record);
if (record.pre == -1) {
record.pre = root.val;
} else {
record.ans = Math.min(record.ans, root.val - record.pre);
record.pre = root.val;
}
dfs(root.right, record);
}
}