How to build tree from level order traversal?

I am not able to solve left view and right view because i cannot understand how to build tree from level order input

Hi Anant, to create a binary tree from level order input, we can build this binary tree by maintaining a queue. Queue is used to maintain those nodes that are not yet processed.

Using a variable count to keep track of the number of children added for the current node.

First, create a root node, assign it as the current node. So starting from index 1 (index 0 is the root), as the count is 0, we add this node as left child of the current node. Increase count. If this node is not ‘-1’, add it to the queue.

Moving to the next index, the count is 1, so we add this as right child of current node, reset count to 0 and update current node (by assigning the current node as the first element in the queue). If this node is not ‘-1’, add it to the queue.

Can you also provide the code for the same please?

You can refer to the code here: https://ide.codingblocks.com/s/60835

1 Like

Thank you, nice explanation!!!

Here is the link to my code to create BT from level order traversal (as per the question on hackerblocks).

https://ide.codingblocks.com/s/61962

Hi Anant, your code is constructing the tree as required. Is there anything specific that you wish to ask?

No, thank you so much!

She made you fool by just copying the code from geeksforgeeks.

1 Like

My Code for Level-Order_Build:
https://ide.codingblocks.com/s/377977

Hope this helps :blush:

1 Like