Problem: In a Binary Tree, Create Linked Lists of all the nodes at each depth.
Input: A binary tree
Output: K linked lists if the height of tree is k. Each linked list will have all the nodes of each level.
Example:
Approach:
Recursion:
- Create a ArrayList of Linked List Nodes.
- Do the level order traversal using queue(Breadth First Search). Click here to know about how to level order traversal.
- For getting all the nodes at each level, before you take out a node from queue, store the size of the queue in a variable, say you call it as levelNodes.
- Now while levelNodes>0, take out the nodes and print it and add their children into the queue. add these to a linked list
- After this while loop put a line break and create a new linked list
This problem is popular in TutorialHorizon, GeeksForGeeks, and StackOverflow. A collection of hundreds of interview questions and solutions are available in our blog at Interview Question
Solution:
No comments:
Post a Comment