1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
// Runtime: 8 ms, faster than 99.49% of C++ online submissions for Validate Binary Search Tree.
// Memory Usage: 21.7 MB, less than 5.21% of C++ online submissions for Validate Binary Search Tree.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root) {
//用无穷大来初始化根节点范围
return isValidBST(root,nullptr,nullptr);
}
private:
bool isValidBST(TreeNode *root,int *inf,int *sup){
//该节点不存在则true
if(!root) return true;
//该节点超出取值范围则为false
if((inf && root->val<=*inf) || (sup && root->val>=*sup)) return false;
//遍历树,只要发生false则返回false
return isValidBST(root->left,inf,&(root->val)) &&
isValidBST(root->right,&(root->val),sup);
}
};
|