Construct Binary Search Tree from Preorder Traversal — LeetCode Day 24 May Challenge

iAwale
2 min readMay 25, 2020

So we are given a list of integers which is the preorder traversal of a binary search tree. We need to generate the binary search tree and return it.

We start of with a root node,

TreeNode root = new TreeNode(preorder[0]);

Before we get on to traversing the given list lets create a function to put every node in its right place.

In the recursive function, we first check which side the element belongs to (left/right) then we check if there is already a node present, if so we check which side the element belongs to of that node, else we create a new node.

public void generate(int element, TreeNode current){        if ( element < current.val){    
if ( current.left == null ){
current.left = new TreeNode(element);
} else{
generate(element, current.left);
}

} else {
if ( current.right == null) {
current.right = new TreeNode(element);
} else{
generate(element, current.right);
}
}

}

Now onto the putting the given list in the correct positions of a Binary Search Tree.

for (int i = 1; i < preorder.length; i++){
generate(preorder[i], root);
}

We then return the root which has the whole binary tree linked to it.

return root;

The full code looks like:

class Solution {
public TreeNode bstFromPreorder(int[] preorder) {

TreeNode root = new TreeNode(preorder[0]);
for ( int i = 1; i < preorder.length; i++){
generate(preorder[i], root);
}

return root;
}

public void generate(int element, TreeNode current){
if ( element < current.val){
if ( current.left == null ){
current.left = new TreeNode(element);
} else{
generate(element, current.left);
}

} else {
if ( current.right == null) {
current.right = new TreeNode(element);
} else{
generate(element, current.right);
}
}
}
}

Full video explanation:

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

iAwale
iAwale

Written by iAwale

Learn Productivity. Learn Growth. Learn Coding. Learn to Build Applications. If you like the content please follow Twitter Youtube

No responses yet

Write a response