LeetCode-面试题 04.05: 合法二叉搜索树

First: Problem’s Description

Second: Problem’s Solution

The sequence created when traversing the BST by the method of inorder is a non decreasing sequence. And if the BST is empty, we should return truerather than false
I don’t recommend to use the recrusing method to solve this problem. Take the following ‘BST’ for example:

if you use recrusing method, we can easily submit code like this:

class Solution {
   
public:
    bool isValidBST(TreeNode* root) {
   
        if(!root)	return true;
        if(root->left && root->left->val >= root->val)	return false;
        if(root->right && root->right->val <= root->val)	return false;
        return isValidBST(root->left) && isValid(root->right);
    }
};

But there is a fatal bug inside the logic shown from the code: you can make sure that each node complies to the BST’s rule that its left node’s value is always smaller than its and its right node’s value always bigger. but you can’t make sure that every node’s value of the current node’s left subtree is always smaller than current root node and so does right subtree. You can check the node 10and the node 15, and you’ll find the bug.

Third: Code For Solution

class Solution {
   
private:
    vector<int> vec;
    void InTraverse(TreeNode* root){
   
        if(root){
   
            InTraverse(root->left);
            vec.push_back(root->val);
            InTraverse(root->right);
        }
    }
    bool MyJudge(TreeNode* root){
   
        if(!root)   return true;
        InTraverse(root);
        if(vec.size() == 1) return true;
        for(int i = 1; i < vec.size(); i++)
            if(vec[i - 1] >= vec[i]) return false;
        return true;
    }
public:
    bool isValidBST(TreeNode* root) {
   
        return MyJudge(root);
    }
};

Four: Processing Result

全部评论

相关推荐

02-26 13:56
已编辑
重庆财经学院 Java
King987:你有实习经历,但是写的也太简单了,这肯定是不行的,你主要要包装实习经历这一块,看我的作品,你自己包装一下吧,或者发我,我给你出一期作品
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
03-30 21:35
爱蜜莉雅碳劝退测开:裁员裁大动脉了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务