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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With