LeetCode 98. 验证二叉搜索树

class Solution {
public:
    vector<int> dfs(TreeNode* root)//依次返回是否是二叉搜索树,最大值最小值
    {
        vector<int> res{1,root->val,root->val};
        if(root->left)
        {
            auto l=dfs(root->left);
            res[1]=max(res[1],l[1]);
            res[2]=min(res[2],l[2]);
            if(root->val<=l[1]||!l[0])  res[0]=0;
        }
        if(root->right)
        {
            auto r=dfs(root->right);
            res[1]=max(res[1],r[1]);
            res[2]=min(res[2],r[2]);
            if(root->val>=r[2]||!r[0])  res[0]=0;
        }
        return res;
    }
    bool isValidBST(TreeNode* root) {
        return dfs(root)[0];
    }
};
posted @ 2023-05-24 14:39  穿过雾的阴霾  阅读(10)  评论(0)    收藏  举报