lc98-Validate Binary Search Tree

要注意的是rely on INT_MIN的问题。

in-order:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 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 {
TreeNode *prev = NULL;
public:
bool isValidBST(TreeNode* root) {
if (!root) return true;
if (root->left) if (!isValidBST(root->left)) return false;;
if (prev && root->val <= prev->val)
return false;
prev = root;
if (root->right) if (!isValidBST(root->right)) return false;
return true;
}
};

pre-order:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 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(root, nullptr, nullptr);
}
bool helper(TreeNode* root, TreeNode* minNode, TreeNode* maxNode) {
if (!root) return true;
if ((minNode && root->val <= minNode->val) || (maxNode && root->val >= maxNode->val))
return false;
return helper(root->left, minNode, root) && helper(root->right, root, maxNode);
}
};