forked from prateekshyap/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConvertIntoSumTree.java
83 lines (70 loc) · 2.14 KB
/
ConvertIntoSumTree.java
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
/*https://practice.geeksforgeeks.org/problems/transform-to-sum-tree/1*/
/*https://binarysearch.com/problems/Elephant-Tree*/
class Solution{
public void toSumTree(Node root){
if (root == null) return;
//get the left subtree and right subtree sum
int leftSum = postOrder(root.left);
int rightSum = postOrder(root.right);
//store the sum in root
root.data = leftSum+rightSum;
}
public int postOrder(Node root)
{
//if root is not null
if (root != null)
{
/*recursion*/
int leftSum = postOrder(root.left);
int rightSum = postOrder(root.right);
//store the root value
int returnValue = root.data;
//add the sum of the subtrees to it
returnValue += leftSum;
returnValue += rightSum;
//store the sum of left and right subtree in root
root.data = leftSum+rightSum;
//return the total sum
return returnValue;
}
//return 0 if root is null
return 0;
}
}
class Solution {
public Tree solve(Tree root) {
recur(root);
return root;
}
public int recur(Tree root)
{
if (root == null) return 0;
recur(root.left);
recur(root.right);
if (root.left != null) root.val += root.left.val;
if (root.right != null) root.val += root.right.val;
return root.val;
}
}
class Solution {
public Tree solve(Tree root) {
recur(root);
return root;
}
public int recur(Tree root)
{
if (root == null) return 0;
if (root.left != null) root.val += recur(root.left);
if (root.right != null) root.val += recur(root.right);
return root.val;
}
}
class Solution {
public Tree solve(Tree root) {
if (root.left == null && root.right == null) return root;
if (root.left == null) root.val += solve(root.right).val;
else if (root.right == null) root.val += solve(root.left).val;
else root.val += solve(root.right).val+solve(root.left).val;
return root;
}
}