zoukankan      html  css  js  c++  java
  • 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.

    思路:

    1) 递归,两边夹

    package bst;
    
    public class ValidateBinarySearchTree {
    
        public boolean isValidBST(TreeNode root) {
            return isValidBST(root, false, Integer.MIN_VALUE, false, Integer.MAX_VALUE);
        }
        
        private boolean isValidBST(TreeNode root, boolean reachMin, int min, boolean reachMax, int max) {
            if (root == null) return true;
            int value = root.val;
            if (value < min || value > max) return false;
            
            if (!reachMin && value == Integer.MIN_VALUE) {
                if (root.left != null) return false;
                return isValidBST(root.right, true, value, reachMax, max);            
            } else if (!reachMax && value == Integer.MAX_VALUE) {
                if (root.right != null) return false;            
                return isValidBST(root.left, reachMin, min, true, value);
            } else if (value > min && value < max) { 
                return isValidBST(root.left, reachMin, min, reachMax, value) && 
                        isValidBST(root.right, reachMin, value, reachMax, max);        
            }
            
            return false;
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
    
        }
    
    }

    2) 类似于中序遍历

    package bst;
    
    public class ValidateBinarySearchTree {
    
        private boolean firstNode = true;
        
        private int lastValue = 0;
        
        public boolean isValidBST(TreeNode root) {
            if (root == null) return true;
            if (!isValidBST(root.left)) return false;
            
            if (!firstNode && root.val <= lastValue) return false;
            firstNode = false;
            lastValue = root.val;
            
            if (!isValidBST(root.right)) return false;
            
            return true;
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
    
        }
    
    }
  • 相关阅读:
    完毕port(CompletionPort)具体解释
    [Java聊天室server]实战之五 读写循环(服务端)
    ImageMagick的安装及使用
    STL学习小结
    ORACLE中%TYPE和%ROWTYPE的使用
    命令模式在MVC框架中的应用
    代码阅读分析工具Understand 2.0试用
    SimpleDateFormat 的线程安全问题与解决方式
    C++垃圾回收机制
    TH文字编辑器开发的第一个游戏,唐伯虎泡妞
  • 原文地址:https://www.cnblogs.com/null00/p/5116903.html
Copyright © 2011-2022 走看看