leetcode-----98. 验证二叉搜索树

代码

/**
 * Definition for a binary tree node.
 * 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) return true;
        return dfs(root)[0];
    }

    vector<int> dfs(TreeNode* root) {
        vector<int> ans({1, root->val, root->val});
        if (root->left) {
            auto t = dfs(root->left);
            if (!t[0] || t[2] >= root->val) ans[0] = 0;
            ans[1] = min(ans[1], t[1]);
            ans[2] = max(ans[2], t[2]);
        }
        if (root->right) {
            auto t = dfs(root->right);
            if (!t[0] || t[1] <= root->val) ans[0]= 0;
            ans[1] = min(ans[1], t[1]);
            ans[2] = max(ans[2], t[2]);
        }
        return ans;
    }
};
上一篇:并行多任务学习论文阅读(四):去偏lasso实现高效通信


下一篇:leetcode—98. 验证二叉搜索树