Construct Binary Search Tree from Preorder Traversal

Construct Binary Search Tree from Preorder Traversal.

Given the preorder traversal of a binary tree. We have to write a code to return the root node of a binary search tree that matches the given preorder traversal.

Before solving this problem, Let’s first understand what is preorder traversal of a binary tree and what is binary search tree.

In preorder traversal, we first visit root node. Then we traverse left subtree and then the right subtree.

What is Binary Search Tree?

In binary search tree, the value of all the nodes in the left sub-tree is less than the value of the root node. Similarly, Value of all the nodes in the right sub-tree is greater than or equal to the value of the root.

We understood the problem statement. Let’s pause for a moment and think how do we approach this problem. In this tutorial, I am going to explain multiple approaches to solve this problem.

Programming Video Tutorials

Construct Binary Search Tree from Preorder Traversal – Java Code

In this problem, we have given a preorder traversal of a binary tree. In preorder traversal, we first visit root then we traverse left and right subtree.

It means the first element of an array is root node. We can simply create a root node by taking the first value of a preorder traversal. Then, traverse the rest of the array element from index 1 to check where we have to place the value (In left or right subtree).

The time complexity of this approach is O(n^2) and it’s space complexity is O(n).

We have solved this problem using Recursion and by using Binary Search Tree property. But, The time complexity of this solution is O(n^2). Can we improve this solution further?

Invert a Binary Tree

Let’s improve our solution and solve this problem in O(n) time complexity. We are already familiar with the property of a Binary Search Tree.

The idea here is to construct a binary search tree by traversing a preorder array. We take the min and max range, Initially it is Integer.MIN_VALUE and Integer.MAX_VALUE.

In Binary Search Tree, the left child should be less than the root node, so the max range would be the value of a root node. The right child should be greater than the root node so it’s min range would be the value of a root node. In this way we construct a binary search tree.

Programming Questions on Binary Tree

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.