-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbt_sumtree.cpp
98 lines (76 loc) · 1.25 KB
/
bt_sumtree.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
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef struct node st;
struct node
{
ll data;
struct node *left,*right;
};
st* newnode(ll data)
{
struct node *temp= (st *)malloc(sizeof(st));
temp->data=data;
temp->left=temp->right=NULL;
return temp;
}
void sum_tree(st *node)
{
if(node==NULL)
return;
sum_tree(node->left);
sum_tree(node->right);
ll ldata,rdata;
if(node->left==NULL)
ldata=0;
else
ldata=node->left->data;
if(node->right==NULL)
rdata=0;
else
rdata=node->right->data;
if(ldata!=0 || rdata!=0)
node->data=ldata+rdata;
}
ll level(struct node *root)
{
if(root==NULL)
return 0;
ll ans=0;
queue<node *> q;
q.push(root);
ll levelsize;
struct node *temp;
while(1)
{
levelsize=q.size();
if(levelsize==0)
break;
while(levelsize>0)
{
temp=q.front();
q.pop();
cout<<temp->data<<" ";
if(temp->left)
q.push(temp->left);
if(temp->right)
q.push(temp->right);
--levelsize;
}
++ans;
}
}
int main()
{
struct node *root=NULL;
root=newnode(10);
root->left=newnode(-2);
root->right=newnode(6);
root->left->left=newnode(8);
root->left->right=newnode(-4);
root->right->left=newnode(7);
root->right->right=newnode(5);
sum_tree(root);
level(root);
return 0;
}