zoukankan      html  css  js  c++  java
  • 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);
        }
    }
  • 相关阅读:
    while练习题
    流程控制之for循环
    流程控制之while循环
    流程控制之if判断
    作业
    基本运算符
    输入输出
    基本数据类型
    变量part2
    JDBC中创建表
  • 原文地址:https://www.cnblogs.com/HuangYJ/p/14189276.html
Copyright © 2011-2022 走看看