[leetcode] Validate Binary Search Tree

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.

https://oj.leetcode.com/problems/validate-binary-search-tree/

 

思路1:递归求解,每个节点有一对valid的范围参数。Tricky的地方是node value的范围覆盖int的边界情况,如果用Integer.MIN_VALUE和MAX_VALUE作为初始边界会有问题。 所以要么用null作为root的开始边界,或者也可以用Long.MIN_VALUE 和 MAX。

思路2:中序遍历,看是否是递增序列。

 

思路1实现

class Solution {
    public boolean isValidBST(TreeNode root) {
        if(root == null){
            return true;
        }
        return isValid(root, null, null);
    }
    
    private boolean isValid(TreeNode node, Integer min, Integer max){
        if(node == null){
            return true;
        }
        if((min!=null && node.val<=min)||(max!=null && node.val>=max)){
            return false;
        }
        return isValid(node.left, min, node.val)&&isValid(node.right, node.val, max);
    }
    
}

 

 

思路2实现

class Solution {
    Integer pre;
    boolean isValid = true;
    public boolean isValidBST(TreeNode root) {
        inorder(root);
        return isValid;
    }
    
    private void inorder(TreeNode root){
        if(root!=null){
            inorder(root.left);
            int cur = root.val;
            if(pre!=null&&cur<=pre){
                isValid = false;
                return;
            }
            pre = cur;
            inorder(root.right);
        }
        
    }

}

 

posted @ 2014-07-02 22:26  jdflyfly  阅读(141)  评论(0编辑  收藏  举报