Given the preorder traversal of a BST design an algorithm to
Given the preorder traversal of a BST, design an algorithm to reconstruct the BST. Please write pseudocode, explain, and state running time.
Solution
Construct BST from given preorder traversal
Set1
the Given preorder traversal of a binary search tree, construct t BST.
given traversal is {10, 5, 1, 7, 40, 50}, then the output should be root of tree.
11
/ \\
6 41
/ \\ \\
2 8 51
O(n^2) time complexity of BST
The first element of preorder traversal is always root. We first construct the root. Then we find the index of first element which is greater than root. Let the index be ‘i’.
They are very values between root and ‘i’ will be part of left subtree, and the values between ‘i+1’ and ‘n-1’ will the part of right subtree of node. Divide given pre1[] at index i and recur for left and right sub-trees.
elements {11, 6, 2, 8, 41, 51,
11 is the first element, so we make it root. Now we look for the first element greater than 11, we find 41. So we know the structure of BST is as following.
11
/ \\
/ \\
{6, 2, 8} {41, 51}
Algorithm: buildTree()
i) Pick a component from Preorder. Increase a Preorder Record Variable
ii) Bst Make another tree hub tree Hub with the information as picked component.
iii) they Discover the picked component\'s file in Inorder. the file be inIndex.
iv) each time Call buildTree for components before inIndex and make the assembled tree as left subtree of tNode.
v) buildTree for components of after inIndex and make the assembled tree as right subtree of tNode.
vi) return treeNode.
