forked from ReciHub/FunnyAlgorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
height.cpp
107 lines (92 loc) · 1.38 KB
/
height.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
#include<bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node*right;
node*left;
node(int d)
{
data=d;
node*right=NULL;
node*left=NULL;
}
};
node* build_tree()
{
int d;
cin>>d;
if(d==-1)
return NULL;
node* root=new node(d);
root->right=build_tree();
root->left=build_tree();
return root;
}
void print(node*root)
{
if(root==NULL)
return;
cout<<root->data<<" ->";
print(root->right);
print(root->left);
}
void preorder(node*root)
{
if(root==NULL)
return;
//follow root left right
cout<<root->data<<" ";
preorder(root->left);
preorder(root->right);
}
void inorder(node*root)
{
if(root==NULL)
return;
//follow left root right
preorder(root->left);
cout<<root->data<<" ";
preorder(root->right);
}
void postorder(node*root)
{
if(root==NULL)
return;
//follow left right root
preorder(root->left);
preorder(root->right);
cout<<root->data<<" ";
}
int height(node*root)
{
if(root==NULL)
return 0;
int left_size=height(root->left);
int right_size=height(root->right);
return max(left_size,right_size)+1;
}
void levelorder(node*root,int k)
{
if(root==NULL)
return;
if (k==1)
{
cout<<root->data<<" ";
return;
}
levelorder(root->left,k-1);
levelorder(root->right,k-1);
}
int main()
{
node*root=build_tree();
print(root);
inorder(root);
cout<<"\n";
postorder(root);
cout<<"\n";
height(root);
cout<<"\n";
return 0;
}