Construct BST from Level Order

You have been given an array ‘levelOrder’ consisting of ‘N’ elements. The array represents the level order traversal of a Binary Search Tree(BST). You need to construct the BST from this level order traversal.

A Binary Search Tree (BST) is a binary tree data structure that has the following properties -

• The left subtree of a node contains only nodes with data less than the node’s data.
• The right subtree of a node contains only nodes with data greater than the node’s data.
• Both the left and right subtrees must also be binary search trees.

For Example:

For the given level order traversal: 5 3 6 2 4 7 

The BST will be:

The Inorder Traversal of this BST is 2 3 4 5 6 7. 
Input Format:
The first line contains an integer ‘T’ denoting the number of test cases. Then each test case follows.

The first line of each test case contains a single integer ‘N’ denoting the length of the array.

The second line of each test case contains ‘N’ single space-separated integers denoting the elements of the array.
Output Format:
For each test case, print the inorder traversal of the BST.

The inorder traversal of a binary tree is the traversal method in which for any node its left subtree is visited first, then the node itself, and then the right subtree. 

Print the output of each test case in a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
1 <= N <= 10^5
0 <= levelOrder[i] <= 10^5

Time Limit: 1 sec
CodingNinjas
author
2y
Using Recursion

The basic idea is that for every number we will find its position in BST using recursion.

Algorithm

  • Let “insertNode” be the recursive function that takes ‘root’ of tree(initially NULL) ...read more
CodingNinjas
author
2y
Optimized Approach

We will create a class ‘NodeRange’ that has:

  1. ‘ptr’, representing a pointer to the node.
  2. ‘leftRange’, representing the minimum value of any of its child node.
  3. ‘rightRange’, representing...read more
Help your peers!
Add answer anonymously...
IEO Makers Fablab Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter