Given a tree encoded as a string, for every node, compute the sum of its subtree values and return the sums tree encoded as a string.
For example, the following tree is given as an encoded string "1{2{3,4},5{6}}" :
1 / \ 2 5 / \ \ 3 4 6After computing the sums, the tree will look like the following:
21 / \ 9 11 / \ \ 3 4 6Therefore the output will be "21{9{3,4},11{6}}"
Example 1:
Input: "1{2{3,4},5{6}}"
Output: "21{9{3,4},11{6}}"
Example 2:
Input: "1{1,1{1,1,1},1}"
Output: "7{1,4{1,1,1},1}"
Walkthroughs of the solution. Try the steps first, then watch to compare approaches.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check