Given a Binary Tree consisting of N nodes and two integers K and L, the task is to add one row of nodes of value K at the Lth level, such that the orientation of the original tree remains unchanged.
Input: K = 1, L = 2
4 5 6
Below is the tree after inserting node with value 1 in the K(= 2) th level.
Input: K = 1, L = 1
4 5 6
Approach: The given problem can be solved by using Breadth First search for traversal of the tree and adding nodes with a given value between a node at level (L – 1) and roots of its left and right subtree. Follow the steps below to solve the problem:
- If L is 1 then make the new node with value K then join the current root to the left of the new node making the new node the root node.
- Initialize a Queue, say Q which is used to traverse the tree using BFS.
- Initialize a variable, say CurrLevel that stores the current level of a node.
- Iterate while Q is not empty() and CurrLevel is less than (L – 1) and perform the following steps:
- Store the size of queue Q in a variable say len.
- Iterate while len is greater than 0 and then pop the front element of the queue and push the left and the right subtree in Q.
- Increment the value of CurrLevel by 1.
- Now again iterate while Q is not empty() and perform the following steps:
- Store the front node of Q in a variable say temp and pop the front element.
- Store the left and the right subtree of temp node in variables, say temp1 and temp2 respectively.
- Create a new node with value K and then join the current node to the left of node temp by assigning the node value to temp.left.
- Again create a new node with value K and then join the current node to the right of node temp by assigning the node value to temp.right.
- Then join the temp1 to the left of the new node i.e., temp.left.left and temp2 to the right of the new node i.e., temp.right.right.
- After completing the above steps, print the tree in level order traversal.
Below is the implementation of the above approach:
1 1 1 2 3 4 5 6
Time Complexity: O(N)
Auxiliary Space: 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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer DSA Live Classes