Problem Link: https://binarysearch.com/problems/Elephant-Tree.
This problem asks for returning the same tree but every node whose value is replaced by sum of its value and all its children’s value. This problem can be solved using recursion. As I mentioned in the other pose, do not just memorize the solutions but understand the thinking process and the logic behind the hood.
For those who are struggling to deal with recursion, try this thinking process that I frequently use.
Thinking Process
Goal: Make each node’s value
= its value
+ sum of all nodes in the left subtree + sum of all nodes in the right subtree
.
- For a leaf node, its value would be
its value
+sum of left subtree
+sum of right subtree
but since it doesn’t have any subtree, it would be itsvalue
+0
+0
. - Okay, we now know that the leaf node’s value should remain the same. This could be a good base condition.
- To generalize,
node->val
=node->val
+sum of left subtree
+sum of right subtree
- Let’s make
dfs(Tree* node)
a function whichreturns the sum
of the current node’s value and all the children. Then, node->val = node->val + dfs(node->left) + dfs(node->right)
- Base condition:
if(root==NULL) return 0;