IBM Interview Question
Software Engineer / DevelopersActually we can do it in O(1) space. Basic idea is, given a root node, recursively build BST on its left sub-tree, then build BST on its right sub-tree. After building each sub-tree, convert sub-BST to Doubly-Linked List, then merge the two Lists to form the ultimate BST. This is done in O(1) space since the merge directly uses the nodes in the lists.
how would you form the ultimate BST of a specific shape, from the doubly linked list constructed from the sub-BST?
Just do any traversal on the binary tree and store the contents in an array. Sort the array. Then do an in-order traversal of the binary tree and assign values from array to the nodes. Complexity: O(n log n) Space complexity: O(n).
- vinod August 17, 2010