List of Depths

Easy
0/40
Average time to solve is 10m
profile
Contributed by
5 upvotes
Asked in companies
FacebookMicrosoft

Problem statement

You are given a binary tree. Your task is to convert this binary tree into a linked list, such that the value at nodes is in the level order form.

Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of the input contains ‘T’ denoting the number of test cases.

The first line of each test case contains elements of the tree in the level order form. The line consists of values of nodes separated by a single space. In case a node is null, we take -1 in its place.

tree2

For example, the level order input for the tree depicted in the above image would be :

15
40 62
-1 -1 10 20
-1 -1 -1 -1

Explanation :

Level 1 :
The root node of the tree is 15.

Level 2 :
Left child of 15 = 40
Right child of 15 = 62

Level 3 :
Left child of 40 = null (-1)
Right child of 40 = null (-1)
Left child of 62 = 10
Right child of 62 = 20

Level 4 :
Left child of 10 = null (-1)
Right child of 10 = null (-1)
Left child of 20 = null (-1)
Right child of 20 = null (-1)
Note :
The above format was just to provide clarity on how the input is formed for a given tree. 

The sequence will be put together in a single line separated by a single space. Hence, for the above-depicted tree, the input will be given as:

15 40 62 -1 -1 10 20 -1 -1 -1 -1
Output Format:
Just return the pointer to the head node of the linked list, no need to print anything,
Constraints:
1 <= T <= 10
1 <= N <= 5 * 10^3
-1 <= A[i] <= 10^5

Time Limit: 1 sec
Sample Input 1:
2
3 5 1 -1 -1 -1 -1
15 40 62 -1 -1 10 20 -1 -1 -1 -1
Explanation for Sample Input 1:
For test case 1:

tree1

The linked list will be: 3 -> 5 -> 1

For test case 2:

tree2

The linked list will be : 15 -> 40 -> 62 -> 10 -> 20
Sample Input 2:
2
9 1 17 -1 14 9 -1 -1 -1 -1 -1 
3 14 -1 4 -1 14 -1 12 -1 -1 -1 
Sample Output 2:
9 1 17 14 9 
3 14 4 14 12 
Hint

Try to use queue Data structure as we need to insert nearest node first.

Approaches (1)
Breadth First Search

A simple intuitive approach would be to traverse the binary tree in level order form using bfs.

Then whenever we see a node, we insert its value in the linked list.

 

Algorithm:

  • Initialize an empty linked list.
  • Starting from the root node run a bfs using a queue.
  • Whenever you encounter a non-empty node, you insert its value in the linked list.
  • Keep doing this recursively until all nodes are visited.
  • Return the head node of the linked list.
Time Complexity

O(N),  where ‘N’ is the number of nodes in the tree.

 

As we will only be traversing the tree, which contains ‘N’ nodes. The time complexity will be O(N)

Space Complexity

O(N),  where ‘N’ is the length of the array.

 

The only space required will be to make a linked list, which is O(N) in space.

Code Solution
(100% EXP penalty)
List of Depths
Full screen
Console