Fork me on GitHub

Validate Binary Search Tree

Description

https://leetcode.com/problems/validate-binary-search-tree/

Solution

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
/**
* 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) {
return helper(LONG_MIN, LONG_MAX, root);
}

bool helper(long lowerBound, long upperBound, TreeNode* root) {
if (root == NULL) return true;
if (root->val <= lowerBound
|| root->val >= upperBound) {
return false;
}

return helper(lowerBound, root->val, root->left)
&& helper(root->val, upperBound, root->right);
}

};