In-place Conversion of Sorted DLL to Balanced BST
In this tutorial, we will learn about in-place conversion of sorted DLL to balanced BST.
Method No. 1 (Simple)
The following is a simple algorithm in which we first find the middle node of the list and make it the root of the tree to be built.
1) Make the middle of the linked list to the root.
2) Go same recursively for right and left half.
O(nLogn) is time complexity, where n indicates the number of nodes in the Linked List.
Method No. 2 (Tricky)
Method 1 builds the tree from the roots to the leaves. We build from the leaves to the root in this method. The concept is to add nodes in BST in the exact order that they show up in Doubly Linked List, to ensure that the tree can really be built in O(n) time. We begin by figuring out the number of nodes in the provided Linked List. Let's say the count is n. After counting nodes, we take the left n/2 nodes and construct the left subtree recursively. After constructing the left subtree, we allocate the middle node to root and connect the left subtree to root. Finally, we recursively build the correct subtree and connect it to the root.
We continue to move the list head pointer to next while constructing the BST so that we get the correct pointer in each recursive call.
The execution of method 2 is shown below. The primary code that generates Balanced BST is illustrated.
Given Linked List 8 9 10 11 12 13 14 PreOrder Traversal of constructed BST 11 9 8 10 13 12 14
Time Complexity will be O(n).
Next TopicMerge Two Balanced Binary Search Trees