Thursday, November 28, 2013

Validate Binary Search Tree LeetCode

Recursion + 利用Binary Search Tree的特点。


  • 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.

Java Code:


public boolean isValidBST(TreeNode root) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        return (root==null)||(isValidBST(root.left) && isValidBST(root.right)
        && checkMax(root.left, root.val)&&checkMin(root.right,root.val));
    }
    
    private boolean checkMax(TreeNode root, int max){
        if(root==null) return true;
        while(root!=null && root.right != null){
            root=root.right;
        }
        return root.val < max;
    }
    
    private boolean checkMin(TreeNode root, int min){
        if(root==null) return true;
        while(root!=null && root.left != null){
            root=root.left;
        }
        return root.val > min;
    }

Updating two new solutions:
First, recursion with null check.
Second, use inorder traversal.


No comments:

Post a Comment