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

 

 

 

posted @ 2014-01-25 13:51  Razer.Lu  阅读(171)  评论(0编辑  收藏  举报