forked from ReciHub/FunnyAlgorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sum_of_nodes.cpp
139 lines (120 loc) · 1.83 KB
/
sum_of_nodes.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#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);
}
void bfs(node*root)
{
queue<node*>q;
q.push(root->data);
while(!q.empty())
{
node*f=q.front();
cout<<f->data<<" ";
q.pop();
//last node condition
if(f->left)
q.push(f->left);
if(f->right)
q.push(f->right);
}
}
int no_nodes(node*root)
{
if(root==NULL)
return 0;
return (no_nodes(root->left)+no_nodes(root->right)+1);
}
int sum_nodes(node*root)
{
if(root==NULL)
return 0;
return (sum_nodes(root->left)+sum_nodes(root->right)+1);
}
int main()
{
node*root=build_tree();
print(root);
inorder(root);
cout<<"\n";
postorder(root);
cout<<"\n";
height(root);
cout<<"\n";
return 0;
}