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.                                            

分析:采用递归的方法,先判断左子树和右子树是不是BST,如果不是返回false,如果左子树和右子树均为BST,那么再比较左子树最大值、根的值、右子树最小值的关系,如果左子树最大值<根值<右子树最小值,则返回true.代码如下:

class Solution {
public:
    bool isValidBST(TreeNode *root) {
        if(!root) return true;
        if((!root->left || root->val > tree_max(root->left)) && (!root->right || root->val < tree_min(root->right)))
            return isValidBST(root->left) && isValidBST(root->right);
        return false;
    }
    int tree_max(TreeNode *root){
        if(!root) return INT_MIN;
         int result = root->val;
        while(root->right) {
            root = root->right;
            result = root->val;
        }
        return result;
    }
    
    int tree_min(TreeNode *root){
        if(!root) return INT_MAX;
        int result = root->val;;
        while(root->left){
            root = root->left;
            result = root->val;
        }
        return result;
    }
};

上面代码有点繁琐,因为有两个函数tree_max和tree_min来计算树的最大值和最小值,以下代码通过维护根值的上限和下限代替最大值最小值,代码简单明了:

 1 class Solution {
 2 public:
 3     bool isValidBST(TreeNode *root) {
 4         return isValidBST(root, LLONG_MIN, LLONG_MAX);
 5     }
 6     bool isValidBST(TreeNode* root, long long lower, long long upper) {
 7         if (root == nullptr) return true;
 8         return root->val > lower && root->val < upper
 9             && isValidBST(root->left, lower, root->val)
10             && isValidBST(root->right, root->val, upper);
11     }
12 };

上面上限和下限用long long类型的原因是结点值可能是INT_MIN和INT_MAX,为防止出错,所以用long long类型。

 

posted on 2014-08-18 12:03  Ryan-Xing  阅读(120)  评论(0编辑  收藏  举报