zoukankan      html  css  js  c++  java
  • [LeetCode] 98. 验证二叉搜索树

    方法一:

    long pre=Long.MIN_VALUE;
        public boolean isValidBST3(TreeNode root){
            if(root==null) return true;
            if(!isValidBST3(root.left)) return false;
            if(root.val<=pre)return false;
            pre=root.val;
            return isValidBST3(root.right);
        }

     方法二:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public boolean isValidBST(TreeNode root) {
            Stack<TreeNode> stack=new Stack<>();
            double inorder=-Double.MAX_VALUE;
    
            while(!stack.isEmpty()||root!=null){
                while (root!=null){
                    stack.push(root);
                    root=root.left;
                }
                root=stack.pop();
                if(root.val<=inorder){
                    return false;
                }
                inorder=root.val;
                root=root.right;
            }
            return true;
        }
    }

     方法三:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public boolean isValidBST(TreeNode root) {
            return helper(root,null,null);
        }
    
        public boolean helper(TreeNode node,Integer lower, Integer upper){
            if(node==null) return true;
            int val=node.val;
            if(lower!=null&&val<=lower) return false;
            if(upper!=null&&val>=upper) return false;
            if(!helper(node.right,val,upper)) return false;
            if(!helper(node.left,lower,val)) return false;
            return true;
        }
    }

  • 相关阅读:
    linux-PAM
    linux runlevel运行级别
    Nmap原理02
    Nmap原理-01选项介绍
    Java面试题04-final关键字详解
    Java面试题03-访问权限控制
    Java设计模式面试题 01
    Linux在Tomcat下部署JavaWeb项目
    Linux中cat、more、less、tail、head命令的区别
    Git 几个重要操作指令对比
  • 原文地址:https://www.cnblogs.com/doyi111/p/12833989.html
Copyright © 2011-2022 走看看