What is the time complexity to construct binary search tree when inord...
For each node in preorder linear search in the order traversal gives left subtree and right subtree.
Time complexity =O(n2)
View all questions of this test
What is the time complexity to construct binary search tree when inord...
Understanding the Problem
To construct a Binary Search Tree (BST) from given inorder and postorder traversals, we need to identify the root and recursively build the left and right subtrees.
Traversal Properties
- Inorder Traversal: This gives the sorted order of elements in a BST.
- Postorder Traversal: This helps identify the root of the tree.
Construction Process
1. Identify the Root: The last element in the postorder array is the root of the current subtree.
2. Find Root's Index: Using the inorder array, find the index of this root element. This divides the inorder array into left and right subtrees.
3. Recursive Construction: Recursively repeat the process for the left and right subtrees.
Time Complexity Analysis
- Finding the Root: For each node, we need to search its index in the inorder array, which takes O(n) time in the worst case.
- Recursive Calls: There are n nodes to process, and if we perform a linear search for each node, the total time taken becomes O(n^2) due to the nested nature of the search within the recursive structure.
Conclusion
Thus, the overall time complexity for constructing the BST from the given inorder and postorder traversals is O(n^2), making option 'C' the correct answer.
This complexity arises primarily from the repeated search operations within the inorder array for each node in the postorder array.