[Leetcode]--Validate Binary Tree

递归解法

[Leetcode]--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;
        }
    }
}
[Leetcode]--Validate Binary Tree

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

[Leetcode]--Validate Binary Tree

[Leetcode]--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) {
        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);
        }
        
    }
}
[Leetcode]--Validate Binary Tree

 

 
[Leetcode]--Validate Binary Tree

[Leetcode]--Validate Binary Tree

上一篇:阿里电话面的几个问题回溯


下一篇:error LNK2001: unresolved external symbol @__security_check_cookie