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;
    }
};



版权声明:本文博客原创文章,博客,未经同意,不得转载。

原文地址:https://www.cnblogs.com/yxwkf/p/4636035.html