标签:style class blog code color art
/** * 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,初最左边和最右边的分支(前者只有上界,后者只有下界),其他节点都有一个上界和下界,将节点值和这个范围比较即可。
LeetCode Validate Binary Search Tree,布布扣,bubuko.com
LeetCode Validate Binary Search Tree
标签:style class blog code color art
原文地址:http://www.cnblogs.com/lailailai/p/3805038.html