Skip to content

Commit 3e1cf1a

Browse files
authored
Replace With Sum of Greater Nodes
1 parent 2a543da commit 3e1cf1a

File tree

1 file changed

+109
-0
lines changed

1 file changed

+109
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
/* Hacker Blocks */
2+
/* Title - Replace With Sum of Greater Nodes */
3+
/* Created By - Akash Modak */
4+
/* Date - 19/09/2020 */
5+
6+
// Given a binary search tree, replace each nodes' data with the sum of all nodes' which are greater or equal than it. Include the current node's data also.
7+
8+
// Input Format
9+
// The first line contains a number n showing the length of the inorder array of BST. The next line contains n integers denoting the elements of the array.
10+
11+
// Constraints
12+
// 2 ≤ N ≤ 10^3
13+
14+
// Output Format
15+
// Print the preorder traversal of the new tree.
16+
17+
// Sample Input
18+
// 7
19+
// 20 30 40 50 60 70 80
20+
// Sample Output
21+
// 260 330 350 300 150 210 80
22+
// Explanation
23+
// The original tree looks like
24+
25+
// 50
26+
// / \
27+
// 30 70
28+
// / \ / \
29+
// 20 40 60 80
30+
// We are supposed to replace the elements by the sum of elements larger than it.
31+
// 80 being the largest element remains unaffected .
32+
// 70 being the second largest element gets updated to 150 (70+80)
33+
// 60 becomes 210 (60 + 70 + 80)
34+
// 50 becomes 260 (50 + 60 + 70 + 80)
35+
// 40 becomes 300 (40 + 50 + 60 + 70 + 80)
36+
// 30 becomes 330 (30 + 40 + 50 + 60 + 70 + 80)
37+
// 20 becomes 350 (20 + 30 + 40 + 50 + 60 + 70 + 80)
38+
39+
// The new tree looks like
40+
41+
// 260
42+
// / \
43+
// 330 150
44+
// / \ / \
45+
// 350 300 210 80
46+
// The Pre-Order traversal (Root->Left->Right) looks like :
47+
// 260 330 350 300 150 210 80.
48+
49+
#include<bits/stdc++.h>
50+
using namespace std;
51+
int temp;
52+
class node{
53+
public:
54+
int data;
55+
node* left,*right;
56+
node(int d){
57+
data=d;
58+
left=right=NULL;
59+
}
60+
};
61+
node* bst(int *a,int start,int end){
62+
if(start>end)
63+
return NULL;
64+
65+
int mid = start + (end-start)/2;
66+
node* root = new node(a[mid]);
67+
root->left = bst(a,start,mid-1);
68+
root->right = bst(a,mid+1,end);
69+
return root;
70+
}
71+
void update(node* root,int &sum){
72+
if(root==NULL)
73+
return ;
74+
75+
// if(root->data == temp)
76+
// return root->data;
77+
78+
update(root->right,sum);
79+
// root->data = rightSum + root->data;
80+
sum = sum+root->data;
81+
root->data = sum;
82+
update(root->left,sum);
83+
}
84+
void preorder(node* root){
85+
if(root==NULL)
86+
return;
87+
88+
cout<<root->data<<" ";
89+
preorder(root->left);
90+
preorder(root->right);
91+
}
92+
int main() {
93+
node *root = NULL;
94+
int n;
95+
cin>>n;
96+
int a[n];
97+
for(int i=0;i<n;i++)
98+
{
99+
cin>>a[i];
100+
if(i==n-1)
101+
temp = a[i];
102+
}
103+
104+
root = bst(a,0,n-1);
105+
int sum=0;
106+
update(root,sum);
107+
preorder(root);
108+
return 0;
109+
}

0 commit comments

Comments
 (0)