Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BST using preorder traversal

Tags:

algorithm

Is it possible to construct a Binary Search Tree Given only its preorder traversal ?

I know a binary tree can be constructed only if both inorder and preorder traversal are given . But my question is specific to Binary Search Tree .

eg: Given : 5,3,1,4,7,8

  Construct : 

       5
    3    7 
  1   4    8
like image 440
premprakash Avatar asked Sep 26 '12 01:09

premprakash


1 Answers

Yes, you can construct a binary search tree from a pre-order traversal. Given a pre-order traversal a_1, ..., a_n, divide it into three segments a_1, (a_2,...,a_k) and (a_{k+1},..,a_n), with the property that a_{k+1} is the first element in the pre-order that is greater than a_1.

Recursively compute the BST T1 of (a_2,...,a_k) and BST T2 of (a_{k+1},..,a_n) and add them as the left and the right subtrees of a new BST rooted at a_1.

like image 135
krjampani Avatar answered Nov 03 '22 00:11

krjampani