zoukankan      html  css  js  c++  java
  • Validate Binary Search Tree——LeetCode

    Given a binary tree, determine if it is a valid binary search tree (BST).

    Assume a BST is defined as follows:

    • The left subtree of a node contains only nodes with keys less than the node's key.
    • The right subtree of a node contains only nodes with keys greater than the node's key.
    • Both the left and right subtrees must also be binary search trees.

    题目大意:给定一个二叉树,判断它是不是二叉搜索树,二叉搜索树满足要求左子树所有的值小于当前节点的值,右子树所有的值大于当前节点,左右子树也分别是二叉搜索树。

    解题思路:

    一、递归验证,每个节点设置一个允许的范围,根节点当然是所有的都可以,其他的节点要大于min并且小于max,并且递归验证左右子树的时候要更新min和max。

     10 ----- binary tree (0)
     /  
    5   15     -------- binary tree (1)
       /  
      6    20

    如上,tree(1)是合法的,但是6比10小,6所在的位置应该是位于 10~15之间,所以这棵树是不合法的。也就是说,需要两个值max, min 来记录当前节点应该的取值范围。那么min和max的更新符合什么规则呢?对于左子树,应该小于根节点,对于右子树,应该大于根节点;对于一个节点来说,它的值应该是左子树的上限,右子树的下限。

    拿上面的树举例来说,节点15的下限是10,上限为null,递归到左子树节点6,下限为10,上限为15,不符合范围要求,返回false。

        public boolean isValidBST(TreeNode root) {
            return doValidate(root, null, null);
        }
    
        private boolean doValidate(TreeNode root, Integer min, Integer max) {
            if (root == null) {
                return true;
            }
            int val = root.val;
            if (min != null && min >= val) {
                return false;
            }
            if (max != null && max <= val) {
                return false;
            }
            return doValidate(root.left, min, val) && doValidate(root.right, val, max);
        }

    二、(推荐)直观,清晰的解题思路:二叉搜索树的中序遍历序列应该是递增的,那么只需要检查中序遍历序列是否是递增序的。

        public boolean isValidBST2(TreeNode root) {
            if (root == null) {
                return true;
            }
            List<Integer> list = new ArrayList<>();
            doValidate(root, list);
            for (int i = 1; i < list.size(); i++) {
                if (list.get(i - 1) >= list.get(i)) {
                    return false;
                }
            }
            return true;
        }
    
        void doValidate(TreeNode node, List<Integer> list) {
            if (node == null) {
                return;
            }
            doValidate(node.left, list);
            list.add(node.val);
            doValidate(node.right, list);
        }
  • 相关阅读:
    .ds_store是什么文件
    style="background-image: url(__HOMEPAGE__/views/IMJ2V2/images/banner2.jpg)"
    前段实现图片懒加载
    thinkphp路由的作用
    thinkphp跨模块调用
    关于肥胖和美国为什么那么多胖子
    php中局部变量和全局变量
    thinkphp5项目--企业单车网站(七)
    thinkphp5项目--企业单车网站(六)
    XSS攻击及防御
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4448949.html
Copyright © 2011-2022 走看看