Skip to content

Commit fee27af

Browse files
authored
Create Replace with Sum of greater nodes
1 parent 247a799 commit fee27af

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
Given a binary search tree, you have to replace each node's data with the sum of all nodes which are greater or equal than it. You need to include the current node's data also.
3+
That is, if in given BST there is a node with data 5, you need to replace it with sum of its data (i.e. 5) and all nodes whose data is greater than or equal to 5.
4+
Note: You don't need to return or print, just change the data of each node.
5+
6+
Input format:
7+
The first line of input contains data of the nodes of the tree in level order form. The data of the nodes of the tree is separated by space. If any node does not have left or right child, take -1 in its place. Since -1 is used as an indication whether the left or right nodes exist, therefore, it will not be a part of the data of any node.
8+
9+
Output format:
10+
In the output, data of the nodes of the tree are printed in level order form. Each level of the tree is printed on a separate line.
11+
12+
Constraints:
13+
Time Limit: 1 second
14+
15+
Sample Input 1 :
16+
8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1
17+
Sample Output 1 :
18+
18
19+
36 10
20+
38 31
21+
25
22+
*/
23+
import java.util.*;
24+
import java.lang.*;
25+
public class Solution {
26+
27+
/*
28+
* Binary Tree Node class
29+
*
30+
* class BinaryTreeNode<T> { T data; BinaryTreeNode<T> left; BinaryTreeNode<T>
31+
* right;
32+
*
33+
* public BinaryTreeNode(T data) { this.data = data; } }
34+
*/
35+
36+
public static void replaceWithLargerNodesSum(BinaryTreeNode<Integer> root) {
37+
// Write your code here
38+
replaceWithLargerNodesSum(root,0);
39+
}
40+
41+
public static int replaceWithLargerNodesSum(BinaryTreeNode<Integer> root, int sum)
42+
{
43+
//Base Case
44+
if(root == null)
45+
return sum;
46+
47+
//Recursive Case
48+
sum = replaceWithLargerNodesSum(root.right,sum);
49+
sum += root.data;
50+
root.data = sum;
51+
return replaceWithLargerNodesSum(root.left,sum);
52+
}
53+
}

0 commit comments

Comments
 (0)