-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbst.cpp
122 lines (106 loc) · 2.81 KB
/
bst.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <iostream>
#include <vector>
#include <stack>
#include <climits>
using namespace std;
struct Node{
bool accessed;
int data;
Node* left;
Node* right;
Node(int v, Node* l=NULL, Node* r=NULL)
: accessed(false), data(v), left(l), right(r) {}
};
class BST{
private:
Node* root;
void insert(Node** np, int v)
{
if(*np == NULL){
*np = new Node(v);
return;
}
if(v < (*np)->data)
insert(&(*np)->left, v);
else
insert(&(*np)->right, v);
}
void traverse(Node* np)
{
if(np == NULL)
return;
traverse(np->left);
cout<<np->data<<endl;
traverse(np->right);
}
void traverse2(Node* np) // 非递归,这种方式的缺点是需要一个accessed标记
{
stack<Node*> s;
s.push(np);
while(!s.empty()){
Node* tmp = s.top();
s.pop();
if(tmp){
if(!tmp->accessed){
s.push(tmp->right);
tmp->accessed = true;
s.push(tmp);
s.push(tmp->left);
}
else{
cout<<tmp->data<<endl;
}
}
}
}
void traverse3(Node* np) // 非递归,无需标记
{
stack<Node*> s;
Node* needp = np;
while(1){
for(auto p = needp; p != NULL; p = p->left)
s.push(p);
if(!s.empty()){
Node* tmp = s.top();
s.pop();
cout<<tmp->data<<endl;
needp = tmp->right;
}
else break;
}
}
public:
BST(const vector<int> nodes)
:root(NULL)
{
for(int i=0; i<nodes.size(); i++)
insert(&root, nodes[i]);
}
void traverse()
{
traverse3(root);
}
bool isBST(Node* np, int* prevp)
{
if(np == NULL)
return true;
bool is = isBST(np->left, prevp);
if(!is) return false;
if(*prevp > np->data)
return false;
cout<<"prev: "<<*prevp<< ", current: "<<np->data<<endl;
*prevp = np->data;
return isBST(np->right, prevp);
}
bool checkBST()
{
int prev = INT_MIN;
return isBST(root, &prev);
}
};
int main()
{
BST tree(vector<int>{5,3,9,6,10,4,2,7});
cout<<tree.checkBST()<<endl;
return 0;
}