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);
            }
            
        }
    }

     

  • 相关阅读:
    干货分享:路由与交换详解大全!
    基于ASCII字符集对比
    css文字两端对齐
    软件版本号(BETA、RC、ALPHA、Release、GA等)
    install和update区别
    Blazor入坑指南
    解决Electron7.0.0的坑,cnpm install electron 安装失败的问题
    Linux查看CPU和内存使用情况
    位运算符在JS中的妙用
    centos7通过yum安装mysql
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3533250.html
Copyright © 2011-2022 走看看