zoukankan      html  css  js  c++  java
  • Validate Binary Tree

    递归解法

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public boolean isValidBST(TreeNode root) {
            return isValidBSTHelper(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
        }
        
        public boolean isValidBSTHelper(TreeNode root, int low, int high){
            
            if(root == null){
                return true;
            }
            
            int value = root.val;
            if( low < value && value < high && 
                isValidBSTHelper(root.left, low, value) && 
                isValidBSTHelper(root.right, value, high)){
                return true;
            }else{
                return false;
            }
        }
    }

    In order traversal 遍历树 将val添加到数组里,然后遍历一遍数组看看数组是否是递增的

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public boolean isValidBST(TreeNode root) {
            if(root == null){
                return true;
            }
            
            ArrayList<Integer> result = new ArrayList<Integer>();
            inOrder(root, result);
            
            
            for(int i = 1; i< result.size(); i++){
                /*注意 root的值不能和左节点或有节点相等*/
                if(result.get(i-1) >= result.get(i)){
                    return false;
                }
            }
            return true;
        }
        
        public void inOrder(TreeNode root, ArrayList<Integer> result){
            if(root == null){
                return;
            }
            
            if(root.left != null){
                inOrder(root.left, result);
            }
            result.add(root.val);
            
            if(root.right != null){
                inOrder(root.right, result);
            }
            
        }
    }

     

  • 相关阅读:
    LAMP的搭建
    Apache安装之后,在浏览器输入ip无法访问
    DNS无法区域传送(axfr,ixfr)
    you do not permission to access / no this server
    http虚拟主机的简单配置训练
    搭建一个简单的dns缓存服务器
    Django——User-Profile
    Django——信号
    Django——中间件
    Django——日志
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3533250.html
Copyright © 2011-2022 走看看