-
Notifications
You must be signed in to change notification settings - Fork 38
/
tree.cpp
66 lines (66 loc) · 1.57 KB
/
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
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdio>
#include <climits>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr){}
};
class Solution {
public:
bool isValidBST(TreeNode *root) {
int prev = INT_MIN;
bool isFirst = true;
return isValidBST(root, prev, isFirst);
}
private:
bool isValidBST(TreeNode *root, int &prev, bool &isFirst) {
if (root == nullptr)
return true;
if (!isValidBST(root->left, prev, isFirst))
return false;
if (isFirst) {
isFirst = false;
} else {
if (root->val <= prev)
return false;
}
prev = root->val;
return isValidBST(root->right, prev, isFirst);
}
};
TreeNode *mk_node(int val)
{
return new TreeNode(val);
}
TreeNode *mk_child(TreeNode *root, TreeNode *left, TreeNode *right)
{
root->left = left;
root->right = right;
return root;
}
TreeNode *mk_child(TreeNode *root, int left, int right)
{
return mk_child(root, new TreeNode(left), new TreeNode(right));
}
TreeNode *mk_child(int root, int left, int right)
{
return mk_child(new TreeNode(root), new TreeNode(left), new TreeNode(right));
}
int main(int argc, char **argv)
{
Solution solution;
TreeNode *root = mk_child(mk_node(INT_MIN), nullptr, nullptr);
//TreeNode *root = mk_child(mk_node(1), mk_node(1), nullptr);
//TreeNode *root = mk_child(mk_node(1), nullptr, mk_node(1));
//TreeNode *root = mk_child(10, 5, 15);
//mk_child(root->right, 6, 20);
//TreeNode *root = mk_child(3,1,4);
cout << solution.isValidBST(root) << endl;
return 0;
}