LeetCode783. 二叉搜索树节点最小距离

二分搜索树:

  1. 每个节点的键值大于左孩子;

  2. 每个节点的键值小于右孩子;

  3. 以左右孩子为根的子树仍为二分搜索树。

☆☆思路:中序遍历,计算相邻数的差值

class Solution {
    int min = Integer.MAX_VALUE;
    TreeNode pre = null; // 记录前一个节点
    public int minDiffInBST(TreeNode root) {
        inOrder(root);
        return min;
    }
    private void inOrder(TreeNode root) {
        if (root == null) return;
        inOrder(root.left);
        if (pre != null) {
            min = Math.min(min, root.val - pre.val);
        }
        pre = root;
        inOrder(root.right);
    }
}
原文地址:https://www.cnblogs.com/HuangYJ/p/14189276.html