Preorder traversal of a BST
You have been given an array/list 'PREORDER' representing the preorder traversal of a BST with 'N' nodes. All the elements in the given array have distinct values.
Your task is to construct a binary search tree that matches the given preorder 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.
Note:
It is guaranteed that a BST can be always constructed from the given preorder traversal. Hence, the answer will always exist.
Example:
From PREORDER = [20, 10, 5, 15, 13, 35, 30, 42] , the following BST can be constructed:
Input Format:
The first line contains an integer 'T' which denotes the number of test cases or queries to be run. Then the test cases follow.
The first line of each test case contains a single integer 'N' denoting the number of nodes in BST.
The second line of each test case contains 'N' single space-separated integers representing the preorder traversal of BST.
Output Format:
Print the inorder traversal of the constructed BST where all nodes are printed in a single-space separated manner.
Output for every test case will be printed in a separate line.
Note:
You don't need to print anything. It has already been taken care of. Just implement the function.
Constraints :
1 <= T <= 100
1 <= N <= 5000
0 <= data <= 10^5
Where 'data' denotes data contained in the nodes of the binary search tree.
Time Limit: 1 sec
CodingNinjas
author
2y
Brute Force Approach
We have a simple Brute Force solution for this problem. We will traverse the PREORDER array, find the left subtree and right subtree and then recursively construct the tree as foll...read more
CodingNinjas
author
2y
Use BST property
The idea is based on the fact that the value of each node in a BST is greater than the value of all nodes in its left subtree and less than the value of all nodes in its right subtree....read more
Help your peers!
Add answer anonymously...
Top UBS C Developer interview questions & answers
Popular interview questions of C Developer
Stay ahead in your career. Get AmbitionBox app
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