-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReplaceNodesBySum.cpp
82 lines (72 loc) · 1.33 KB
/
ReplaceNodesBySum.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
#include <iostream>
#include <queue>
using namespace std;
class Node{
public:
int data;
Node* right;
Node* left;
Node(int value){
data=value;
right=NULL;
left=NULL;
}
};
Node* CreateBTLevelWise(){
Node* root=NULL;
int num;
cin>>num;
if(num==-1) return NULL;
root=new Node(num);
queue<Node*> q;
q.push(root);
while(!q.empty()){
Node* curNode=q.front();
q.pop();
int leftData;
cin>>leftData;
if(leftData!=-1){
curNode->left=new Node(leftData);
q.push(curNode->left);
}
int rightData;
cin>>rightData;
if(rightData!=-1){
curNode->right=new Node(rightData);
q.push(curNode->right);
}
}
return root;
}
void PrintBTLevelWise(Node* root){
if(root==NULL) return;
queue<Node*> q;
q.push(root);
q.push(NULL);
while(!q.empty()){
Node* curNode=q.front();
q.pop();
if(curNode==NULL){
cout<<endl;
if(!q.empty()) q.push(NULL);
continue;
}
cout<<curNode->data<<" ";
if(curNode->left) q.push(curNode->left);
if(curNode->right) q.push(curNode->right);
}
}
int ReplaceNodeBySum(Node* root){
if(root==NULL) return 0;
int left=ReplaceNodeBySum(root->left);
int right=ReplaceNodeBySum(root->right);
int curSum=left+right+root->data;
root->data=left+right;
return curSum;
}
int main(){
Node* root=CreateBTLevelWise();
ReplaceNodeBySum(root);
PrintBTLevelWise(root);
return 0;
}