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

    按题意检查即可

    可以递归,会比较好理解,逐渐收缩max和min

    class Solution {
        public boolean isValidBST(TreeNode root) {
            return helper(root, Long.MAX_VALUE, Long.MIN_VALUE);
            
        }
        private boolean helper(TreeNode root , long max, long min){
            if(root == null)
                return true;
            if(root.val >= max || root.val <= min)
                return false;
            
            return helper(root.left, root.val, min) && helper(root.right, max, root.val);
        }
        
    
    }

    也可以迭代,利用中序遍历

    class Solution {
        public boolean isValidBST(TreeNode root) {
            Stack<TreeNode> stack = new Stack<>();
            if(root == null)
                return true;
            TreeNode pre = null;
            
            while(root != null || !stack.isEmpty()){
                while(root!= null){
                    stack.push(root);
                    root = root.left;
                }
                root = stack.pop();
                if(pre != null && root.val <= pre.val)
                    return false;
                pre = root;
                root = root.right;
            }
            return true;
            
        }
        
    
    }
  • 相关阅读:
    python之基础2
    python之文件2
    python之入门2
    python之入门
    python之多并发2
    python之面向对象2
    python之MySQL系列
    python之文件
    python之多并发
    Google身份验证器详解
  • 原文地址:https://www.cnblogs.com/hwd9654/p/11361486.html
Copyright © 2011-2022 走看看