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 the 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
Its tree representation is shown below
Elements at level k = 2 are 6, 4, 1, 3
product of these elements = 6 * 4 * 1 * 3 = 72
Input: Tree = “(8(3(2()())(6(5()())()))(5(10()())(7(13()())())))”
k = 3
Elements at level k = 3 are 5, 1 and 3
product of these elements = 5 * 1 * 3 = 15
Approach: The idea is to treat the string as a tree without actually creating one, and simply traverse the string recursively in Postorder Fashion and consider nodes which are at level k only.
Below is the implementation of above approach:
Time Complexity: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Product of nodes at k-th level in a tree represented as string
- Sum of nodes at k-th level in a tree represented as string
- Sum of all nodes at Kth level in a Binary Tree
- Nodes at Kth level without duplicates in a Binary Tree
- Difference between sums of odd level and even level nodes of a Binary Tree
- Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree
- Difference between sums of odd level and even level nodes in an N-ary Tree
- Print nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately
- Find Maximum Level Sum in Binary Tree using Recursion
- Connect Nodes at same Level (Level Order Traversal)
- Prime Numbers present at Kth level of a Binary Tree
- Find the numbers present at Kth level of a Fibonacci Binary Tree
- Kth ancestor of all nodes in an N-ary tree using DFS
- Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
- Check if all nodes of the Binary Tree can be represented as sum of two primes
- Count the number of nodes at given level in a tree using BFS.
- Level with maximum number of nodes using DFS in a N-ary tree
- Construct a Binary in Level Order using Recursion
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Find maximum level product in 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.