首页 > 代码库 > LeetCode :: Validate Binary Search Tree[详细分析]

LeetCode :: Validate Binary Search Tree[详细分析]


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的定义,任一节点的子孙分别递归满足,左子孙小于该节点,右子孙大于该节点;只要判断这个就OK了;
一个主意点:在递归程序里面,仅判断一个节点大于左儿子小于右儿子是不够的,这样对于左儿子的右儿子以及右儿子的左儿子的
错误判断不到,因此需要将节点值变为边界值,递归下传;
代码如下:
class Solution {
public:
    bool isValidBST(TreeNode *root) {
        return check(root, INT_MIN, INT_MAX);
    }
    
private:
    bool check(TreeNode *root, int left, int right){
        if(root == NULL)
            return true;
        return (root->val > left) && (root->val < right) 
               && check(root->left, left, root->val) &&check(root->right, root->val, right); 
    }//这里的左儿子的左界用上面传下来的,右界用节点值,右儿子镜面对称
};

PS:按照注意点提到的思路写的错误代码
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isValidBST(TreeNode *root) {
        if (root == NULL)
            return true;
            
        bool bleft = true, bright = true;
        if (root->left != NULL){
            if (root->val > root->left->val){    //注意这里检验以及递归是不能保证根节点大于左边所有的,矛盾在于,左儿子的右儿子,以及右儿子的左儿子;
                bleft = isValidBST(root->left);
            }
            else{
                return false;
            }
        }
        
        if (root->right != NULL){
            if (root->val < root->right->val){
                bright = isValidBST(root->right);
            }
            else{
                return false;
            }
        }
        return bleft && bright;
    }
};