-
Notifications
You must be signed in to change notification settings - Fork 0
/
0098_validate_binary_search_tree.cpp
34 lines (31 loc) · 1.12 KB
/
0098_validate_binary_search_tree.cpp
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
31
32
33
34
/*
* Given a binary tree, determine if it is a valid binary search tree(BST).
*
* Assume a BST is defined as follows:
* The left subtree of a node contains only nodes with keys less than the node's key.
* The right subtree of a node contains only nodes with keys greater than the node's key.
* Both the left and right subtrees must also be binary search trees.
*/
/*
* 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 helper(TreeNode *node, long lower, long upper) {
if (!node) return true;
return lower < node->val && node->val < upper &&
helper(node->left, lower, node->val) &&
helper(node->right, node->val, upper);
}
bool isValidBST(TreeNode *root){
return helper(root, LONG_MIN, LONG_MAX);
}
};