Sum of nodes at k-th level in a tree represented as string
Last Updated : 23 Jul, 2025
Given an integer k and a binary tree in string format. Every node of a tree has a value in the range of 0 to 9. The task is to find the sum of elements at the k-th level from the root. The root is at level 0. Tree is given in the form: (node value(left subtree)(right subtree))
Examples:
Input : s = "(0(5(6()())(4()(9()())))(7(1()())(3()())))" , k = 2 Output : 14 Explanation: The tree representation is shown below:
[Naive Approach] Using Pre-order traversal - O(n) Time and O(h) Space
The idea is to treat the string as tree without actually creating one, and simply traverse the string recursively in pre-ordermanner and consider nodes that are at level k only.
Note: This approach may give Stack Overflow error.
Below is the implementation of the above approach:
Output
14
[Expected Approach] Using Iterative Method - O(n) Time and O(1) Space
The idea is to iterate over the string and use the brackets to find the level of the current node. If current character is '(', then increment the level. If current character is ')', then decrement the level.
Step by step approach:
Initialize two variables,say level = -1 and sum = 0
for each character 'ch' in 's'
if ch == '(' then increment the level.
else if ch == ')' then decrement the level.
else if level == k, then add the node value to sum.
return sum.
Below is the implementation of the above approach: