-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy path4-5.cpp
More file actions
81 lines (70 loc) · 1.59 KB
/
Copy path4-5.cpp
File metadata and controls
81 lines (70 loc) · 1.59 KB
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
80
81
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
class TreeNode{
public:
TreeNode* left;
TreeNode* right;
int val;
TreeNode(int x):val(x),left(NULL),right(NULL){}
};
static int last = INT_MIN;
class Solution{
public:
void inOrder(TreeNode* root, vector<int> &l){
if (root==NULL){
return;
}else{
inOrder(root->left,l);
cout << root->val << " ";
l.push_back(root->val);
inOrder(root->right,l);
}
}
bool checkbst(TreeNode* root){
vector<int> l;
inOrder(root,l);
for (int i=1;i<l.size();i++){
if (l[i]<l[i-1]){
return false;
}
}
return true;
}
bool checkbst2(TreeNode* root){
if (root==NULL){
return true;
}else{
if (!checkbst2(root->left)){return false;}
if (root->val<last){return false;}
last=root->val;
if (!checkbst2(root->right)){return false;}
return true;
}
}
};
int main(){
//construct tree
TreeNode* root = new TreeNode(3);
root->left = new TreeNode(1);
root->right = new TreeNode(5);
root->left->left = new TreeNode(0);
root->left->right = new TreeNode(2);
root->right->left = new TreeNode(4);
root->right->right = new TreeNode(6);
root->right->right->right = new TreeNode(7);
root->right->right->right->right = new TreeNode(8);
Solution sol;
if (sol.checkbst(root)){
cout << "This is a BST" << endl;
}else{
cout << "This is NOT a BST" << endl;
}
if (sol.checkbst2(root)){
cout << "This is a BST" << endl;
}else{
cout << "This is NOT a BST" << endl;
}
return 0;
}