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

     

  • 相关阅读:
    Create方法失效而没有提示错误信息
    JS弹出窗口控制
    本周活动
    JavaScript的初步了解
    关于PHP接收文件的资料
    mvc模式改进网站结构
    一周动态
    排序
    Java的内存泄漏
    Android笔记
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3533250.html
Copyright © 2011-2022 走看看