首页 > 代码库 > LeetCode Validate Binary Search Tree

LeetCode Validate Binary Search Tree

/** * 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) {        return dfs(root, 0, 0, 0);    }        bool dfs(TreeNode *root, int lower, int upper, int part) {        if (root == NULL) return true;        if ((part & 0x1) && lower >= root->val) return false;        if ((part & 0x2) && upper <= root->val) return false;        return dfs(root->left, lower, root->val, part | 0x2)                 && dfs(root->right, root->val, upper, part | 0x1);    }};

dfs,初最左边和最右边的分支(前者只有上界,后者只有下界),其他节点都有一个上界和下界,将节点值和这个范围比较即可。