-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
50 lines (40 loc) · 1.03 KB
/
Copy pathsolution.cpp
File metadata and controls
50 lines (40 loc) · 1.03 KB
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
/* Structure for Tree Node
class Node {
public:
int data;
Node* left;
Node* right;
Node(int val) {
data = val;
left = nullptr;
right = nullptr;
}
};
*/
class Solution
{
public:
// Helper function to convert tree and return
// total sum of original subtree
int solve(Node *root)
{
// Base case
if (root == NULL)
return 0;
// Recursively get left subtree sum
int leftSum = solve(root->left);
// Recursively get right subtree sum
int rightSum = solve(root->right);
// Store original node value before changing it
int originalValue = root->data;
// Update current node with sum of left and right subtree
root->data = leftSum + rightSum;
// Return total original subtree sum to parent
return originalValue + root->data;
}
void toSumTree(Node *root)
{
// Start recursive transformation
solve(root);
}
};