-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathreplace_each_node.cpp
96 lines (79 loc) · 1.46 KB
/
replace_each_node.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
/*Problem Statement:
You are given a binary tree,
your task is to replace each node of the binary tree by the sum of its child nodes. */
#include <bits/stdc++.h>
using namespace std;
class node
{
public:
int data;
node * left;
node * right;
node(int d)
{
data = d;
left = NULL;
right = NULL;
}
};
node* buildTree()
{
int d;
cin >> d;
if (d == -1)
{
return NULL;
}
node *root = new node(d);
root->left = buildTree();
root->right = buildTree();
return root;
}
void print(node *root)
{
if (root == NULL)
{
return;
}
cout << root->data << " ";
print(root->left);
print(root->right);
}
int replaceSum(node *root)
{
if (root == NULL)
{
return 0;
}
if (root->left == NULL and root->right == NULL)
{
return root->data;
}
int lsum = replaceSum(root->left);
int rsum = replaceSum(root->right);
int temp = root->data;
root->data = lsum + rsum;
return temp + root->data;
}
int main()
{
cout << "Enter the nodes of the binary tree: " << endl;
node *root = buildTree();
cout << "Initial tree: "<<endl;
print(root);
replaceSum(root);
cout << "Final tree: "<<endl;
print(root);
return 0;
}
/*
Example:
Input:-
Enter the nodes of the binary tree:
1 2 -1 -1 3 -1 -1
Output:-
Initial tree: 1 2 3
Final tree: 5 2 3
Time Complexity: O(n)
Space Complexity: O(n)
*/