zoukankan      html  css  js  c++  java
  • 验证二叉搜索树

    给定一个二叉树,判断其是否是一个有效的二叉搜索树。

    一个二叉搜索树具有如下特征:

    • 节点的左子树只包含小于当前节点的数。
    • 节点的右子树只包含大于当前节点的数。
    • 所有左子树和右子树自身必须也是二叉搜索树。

    示例 1:

    输入:
        2
       / 
      1   3
    输出: true


    示例 2:

    输入:
        5
       / 
      1   4
         / 
        3   6
    输出: false
    解释: 输入为: [5,1,4,null,null,3,6]。
         根节点的值为 5 ,但是其右子节点值为 4 。

    解题思路:

    由二叉搜索树的特点可知,若对其进行中序遍历,得到的则是一个递增序列。

    故采用中序遍历验证二叉搜索树的有效性。

    即将每一个节点的值与其上一个节点的值相比较,若大于继续进行直到遍历整个二叉树,若小于则不是有效的二叉树。

    实现代码:

        // 记录比较结果
        private static boolean res = true;
        // 记录上个节点的值
        private static long max = Long.MIN_VALUE; 
    
        private  static void test(TreeNode root) {
            if (!res || root == null) return;
            test(root.left);
    
            if (root.val > max) max = root.val;
            else { res = false; return;}
    
            test(root.right);
        }
    
    
        public static boolean isValidBST(TreeNode root) {
            if (root == null) return true;
            test(root);
            return res;
        }

    对于递归函数中所有函数都使用到的变量要设为类变量或实例变量,不能是递归函数的局部变量。

    如代码中的  变量res与max。

    如下代码则会出现错误:

        private  static void test(TreeNode root, boolean res, int max) {
    
            if (!res || root == null) return;
            test(root.left, res, max);
    
            if (root.val > max) max = root.val;
            else { res = false; return;}
    
            test(root.right, res, max);
        }

    每次递归调用的并不是同一个res与max,只是将二者的值传入调用函数。

  • 相关阅读:
    python基础语法_9-2函数式编程
    python基础语法_9-1闭包 装饰器补充
    python基础语法_9-0函数概念
    python基础语法_8循环语句
    python基础语法_7运算符
    python基础语法_3面向对象
    python基础语法_2基本数据类型
    python基础语法_python中的布尔类型详解
    用户需求分析
    结对编程-词频统计(北航暑期软工培训) 郑琪 李泓毅
  • 原文地址:https://www.cnblogs.com/deltadeblog/p/9107912.html
Copyright © 2011-2022 走看看