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 product of elements at K-th level from root. The root is at level 0.
Note : 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 : 72 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 = 72 Input : tree = "(8(3(2()())(6(5()())()))(5(10()())(7(13()())())))" k = 3 Output : 15 Elements at level k = 3 are 5, 1 and 3 sum of digits of these elements = 5 * 1 * 3 = 15
1. Input 'tree' in string format and level k 2. Initialize level = -1 and product = 1 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 product = product * (ch-'0') 4. Print product
Time Complexity: O(n)
- Product of nodes at k-th level in a tree represented as string using Recursion
- Sum of nodes at k-th level in a tree represented as string
- Difference between sums of odd level and even level nodes of a Binary Tree
- Sum of all nodes at Kth level in a Binary Tree
- Nodes at Kth level without duplicates in a Binary Tree
- Swap Nodes in Binary tree of every k'th level
- Level with maximum number of nodes using DFS in a N-ary tree
- Count the number of nodes at given level in a tree using BFS.
- Find maximum level product in Binary Tree
- Count nodes with two children at level L in a Binary Tree
- Print nodes between two given level numbers of a binary tree
- Print all the nodes except the leftmost node in every level of the given binary tree
- Print all nodes except rightmost node of every level of the Binary Tree
- Print even positioned nodes of odd levels in level order of the given binary tree
- Print odd positioned nodes of odd levels in level order of the given binary tree
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.