Given an integer ‘K’ and a binary tree in string format. Every node of a tree has value in range from 0 to 9. We need to find sum of elements at K-th level from root. The root is at level 0.
Tree is given in the form: (node value(left subtree)(right subtree))
Input : tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))" k = 2 Output : 14 Its tree representation is shown below Elements at level k = 2 are 6, 4, 1, 3 sum of the digits of these elements = 6+4+1+3 = 14 Input : tree = "(8(3(2()())(6(5()())()))(5(10()())(7(13()())())))" k = 3 Output : 9 Elements at level k = 3 are 5, 1 and 3 sum of digits of these elements = 5+1+3 = 9
1. Input 'tree' in string format and level k 2. Initialize level = -1 and sum = 0 3. for each character 'ch' in 'tree' 3.1 if ch == '(' then --> level++ 3.2 else if ch == ')' then --> level-- 3.3 else if level == k then sum = sum + (ch-'0') 4. Print sum
Time Complexity: O(n)
Recursive Method: The idea is to treat the string as tree without actually creating one, and simply traverse the string recursively in Postorder Fashion and consider nodes which are at level k only.
Following is the C++ implementation of the same:
Time Complexity: O(n)
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Tree Traversals (Inorder, Preorder and Postorder)
- Find the node with minimum value in a Binary Search Tree
- Write a program to Calculate Size of a tree | Recursion
- Write a Program to Find the Maximum Depth or Height of a Tree
- Write a program to Delete a Tree
- If you are given two traversal sequences, can you construct the binary tree?
- Convert a Binary Tree into its Mirror Tree
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Lowest Common Ancestor in a Binary Search Tree.
- The Great Tree-List Recursion Problem.
- Check sum of Covered and Uncovered nodes of Binary Tree
- Level Order Tree Traversal
- Program to count leaf nodes in a binary tree
- A program to check if a binary tree is BST or not
- Level order traversal in spiral form