-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtreetest.cpp
108 lines (96 loc) · 1.66 KB
/
treetest.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
//
//
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* createTree(int a[], int n)
{
if (n<=0) return NULL;
TreeNode **tree = new TreeNode*[n];
for(int i=0; i<n; i++) {
tree[i] = new TreeNode(a[i]);
}
int pos=1;
for(int i=0; i<n && pos<n; i++) {
if (tree[i])
{
tree[i]->left = tree[pos++];
if (pos<n)
{
tree[i]->right = tree[pos++];
}
}
}
return tree[0];
}
void printTree_post_order(TreeNode *root)
{
if (root == NULL){
//cout << "# ";
return ;
}
printTree_post_order(root->left);
printTree_post_order(root->right);
cout << root->val << " ";
}
void printTree_bylevel(TreeNode* root)
{
if(!root) return;
queue<TreeNode*> q;
q.push(root);
q.push(NULL);
int pos = 18;
for(int i = 0; i < pos; ++i)
{
cout << " ";
}
cout << endl;
pos = 0;
while(!q.empty())
{
TreeNode* p = q.front(); q.pop();
if(p)
{
cout << p -> val << " ";
if( p -> left) q.push( p-> left);
if( p -> right) q.push( p -> right);
pos +=1;
}
else
{
if(q.empty()) return;
q.push(NULL);
cout << endl;
for(int i = 0; i < pos; ++i)
{
cout << " ";
}
}
}
}
void printArray(vector<int> v)
{
for(int i=0; i<v.size(); i++){
cout << v[i] << " ";
}
cout << endl;
}
int main(int argc, const char * argv[]) {
int a[] = {5, 3, 20, 21, 7, 12, 8};
TreeNode* p = createTree(a, sizeof(a)/sizeof(int));
printTree_post_order(p);
cout << endl;
printTree_bylevel(p);
vector<int> v = postorderTraversal(p);
printArray(v);
cout << endl;
return 0;
}