LeetCode530-二叉搜索树的最小绝对差

LeetCode530-二叉搜索树的最小绝对差

中序递归实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int pre = -1;
int min = Integer.MAX_VALUE;

public int getMinimumDifference(TreeNode root) {
inorderTraversal(root);
return min;
}

private void inorderTraversal(TreeNode node) {
if (node == null) {
return;
}
inorderTraversal(node.left);
if (pre==-1){
pre = node.val;
}else {
min = Math.min(min, node.val - pre);
pre = node.val;
}
inorderTraversal(node.right);
}