zoukankan      html  css  js  c++  java
  • 98. Validate Binary Search Tree

    一、题目

      1、审题

      

      2、分析

        判断所给二叉树是否时一个二分查找树。(left < top < right)

    二、解答

      1、思路:

        方法一、

          采用中序遍历,将遍历的节点值放入一个 List 中,再判断 List 中的元素是否时升序的即可。

    public boolean isValidBST(TreeNode root) {
        
            if(root == null)
                return true;
            
            List<Integer> list = new ArrayList<Integer>();
            Stack<TreeNode> stack = new Stack<TreeNode>();
            TreeNode cur = root;
            while(cur != null || !stack.isEmpty()) {
                while(cur != null) {
                    stack.add(cur);
                    cur = cur.left;
                }
                
                cur = stack.pop();
                list.add(cur.val);
                cur = cur.right;
            }
            
            int tmp = list.get(0);
            for(int i = 1; i < list.size(); i++) {
                if(list.get(i) < tmp)
                    return false;
                tmp = list.get(i);
            }
            
            return true;
        }

      

      方法二、

        采用中序遍历,直接在便利过程中进行判断是否符合二叉查找树条件。(无须用 List 存储结点)

    public boolean isValidBST2(TreeNode root) {
            
            if(root == null)
                return true;
            
            Stack<TreeNode> stack = new Stack<TreeNode>();
            TreeNode cur = root;
            TreeNode pre = null;
            while(cur != null || !stack.isEmpty()) {
                while(cur != null) {
                    stack.add(cur);
                    cur = cur.left;
                }
                
                cur = stack.pop();
                if(pre != null && pre.val >= cur.val)
                    return false;
                pre = cur;
                cur = cur.right;
            }
            
            return true;
        }

        

        方法三、

          利用递归判断 left 是否小于当前结点值,right 是否大于当前结点值。

    public boolean isValidBST3(TreeNode root) {
            
            return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
        }
        private boolean isValidBST(TreeNode root, long minValue, long maxValue) {
            
            if(root == null)
                return true;
            
            if(root.val >= maxValue || root.val <= minValue)
                return false;
            
            return isValidBST(root.left, minValue, root.val) && isValidBST(root.right, root.val, maxValue);
        }
  • 相关阅读:
    How to become a hacker
    逻辑地址、线性地址、物理地址和虚拟地址
    java configuration
    Java 理论与实践: 变还是不变?
    Teach Yourself Programming in Ten Years
    border padding margin , the difference among them
    hashCode方法,equals方法,HashSet,HasMap之间的关系
    工程名 显示红色叹号
    记The_C_Programming_Language的错误
    VIM简单介绍学习1
  • 原文地址:https://www.cnblogs.com/skillking/p/9709874.html
Copyright © 2011-2022 走看看