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

    /**
     * 98. Validate Binary Search Tree
     * 1. Time:O(n)  Space:O(n)
     * 2. Time:O(n)  Space:O(n)
     */
    
    // 1. Time:O(n)  Space:O(n)
    class Solution {
        public boolean isValidBST(TreeNode root) {
            return helper(root,null,null);
        }
    
        private boolean helper(TreeNode root, Integer lower, Integer upper){
            if(root == null) return true;
            if(lower!=null && root.val<=lower) return false;
            if(upper!=null && root.val>=upper) return false;
            return helper(root.left,lower,root.val) && helper(root.right,root.val,upper);
        }
    }
    
    // 2. Time:O(n)  Space:O(n)
    class Solution {
        public boolean isValidBST(TreeNode root) {
            if(root==null) return true;
            Stack<TreeNode> stack = new Stack<>();
            TreeNode pre = null;
            while(!stack.isEmpty() || root!=null){
                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;
        }
    }
    
  • 相关阅读:
    AutoFac学习笔记
    AutoMapper学习笔记
    ROSLYN 查看C#方法执行次数
    log4net 动态创建文件名
    WPF可切换按钮,iOS风格
    咕咕咕
    贪吃的小J
    UK Day15
    UK Day15
    UK Day15
  • 原文地址:https://www.cnblogs.com/AAAmsl/p/12842045.html
Copyright © 2011-2022 走看看