-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate_binary_search_tree.cpp
79 lines (70 loc) · 1.85 KB
/
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
* =====================================================================================
*
* Filename: validate_binary_search_tree.cpp
*
* Description: 98. Validate Binary Search Tree. Given a binary tree, determine if
* it is a valid binary search tree (BST).
*
* Version: 1.0
* Created: 02/28/19 01:50:49
* Revision: none
* Compiler: gcc
*
* Author: [email protected]
* Organization:
*
* =====================================================================================
*/
#include <cstdio>
#include <stack>
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// Recursive
class Solution1 {
public:
bool isValidBST(TreeNode* root) { return doValidate(root, NULL, NULL); }
private:
bool doValidate(TreeNode* node, TreeNode* min, TreeNode* max) {
if (node == NULL) {
return true;
}
if ((min != NULL && node->val <= min->val) || (max != NULL && node->val >= max->val)) {
return false;
}
return (doValidate(node->left, min, node) && doValidate(node->right, node, max));
}
};
// Inorder traversal
class Solution2 {
public:
bool isValidBST(TreeNode* root) {
TreeNode* pre = nullptr;
std::stack<TreeNode*> nodes;
while (root != nullptr || !nodes.empty()) {
while (root != nullptr) {
nodes.push(root);
root = root->left;
}
root = nodes.top();
nodes.pop();
if (pre != nullptr && pre->val >= root->val) {
return false;
}
pre = root;
root = root->right;
}
return true;
}
};
using Solution = Solution2;
int main(int argc, char* argv[]) {
TreeNode* root = NULL;
auto valid = Solution().isValidBST(root);
printf("Is a valid binary search tree? %s\n", (valid ? "Yes" : "No"));
return 0;
}