本题仍然是二叉搜索树,由于中序遍历搜索树是按照由小到大排列,因此只需要将树中序遍历,用一个pre树记录当前节点的前一个节点,然后判断结果大小,最终输出即可。这里pre容易搞错,以上图为例,当前节点为2时,我刚开始还以为pre是3,其实是1。因为中序遍历先把左子树节点遍历完以后再往回遍历,而pre记录的当前节点就是最小节点,从最小节点开始慢慢由小到大遍历。这里后期回顾要好好复习.
/**
* 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 pre;
int ans;
public int getMinimumDifference(TreeNode root) {
ans = Integer.MAX_VALUE;
pre = -1;
dfs(root);
return ans;
}
public void dfs(TreeNode root) {
if (root == null) {
return;
}
dfs(root.left);
if (pre == -1) {
pre = root.val;
} else {
ans = Math.min(ans, root.val - pre);
pre = root.val;
}
dfs(root.right);
}
}