leetcode 94: Valid Binary Search Tree

Validate Binary Search TreeAug 31 '12

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

recursive approach:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 
 //null, root, {1,2,3} {2,3,1} {1,1} {1,#,1}
 
public class Solution {
    public boolean isValidBST(TreeNode root) {
        // Start typing your Java solution below
        // DO NOT write main() function
        
        return valRec( root, Integer.MIN_VALUE, Integer.MAX_VALUE);
    }
    
    private boolean valRec(TreeNode root, int low, int high) {
        if(root==null) return true;
        int x = root.val;
        if( x<=low || x>=high ) return false;
        
        return valRec(root.left, low, x) && valRec(root.right, x, high);  
    }
}



non-recursive approach:


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 
 //null, root, {1,2,3} {2,3,1} {1,1} {1,#,1}
 
public class Solution {
    public boolean isValidBST(TreeNode root) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(root==null) return true;
        
        Stack<TreeNode> stack = new Stack<TreeNode>();
        Stack<Pair> pairStack = new Stack<Pair>();
        
        stack.push( root);
        pairStack.push( new Pair(Integer.MIN_VALUE, Integer.MAX_VALUE) );
        
        while(!stack.isEmpty() ){
            TreeNode n = stack.pop();
            Pair pair = pairStack.pop();
            int x = n.val;
            if( x<=pair.low || x>=pair.high) return false;
            if( n.left!=null) {
                stack.push( n.left);
                pairStack.push( new Pair(pair.low, x) );
            }
            
            if( n.right!=null) {
                stack.push( n.right);
                pairStack.push( new Pair(x, pair.high) );
            }
        }
        
        return true;
    }
    
    class Pair{
        int low;
        int high;
        Pair(int low, int high) {
            this.low=low;
            this.high=high;
        }
    }
}


posted @ 2013-03-01 14:13  西施豆腐渣  阅读(128)  评论(0编辑  收藏  举报