## Wednesday, February 26, 2014

### Sorted Linked List to Balanced BST

Problem : Given a Singly Linked List which has data members sorted in ascending order. Construct a Balanced Binary Search Tree which has same data members as the given Linked List.

Example :
```Input: Linked List 1->2->3->4->5->6->7
Output: A Balanced BST
4
/   \
2     6
/  \   / \
1   3  4   7
```

Lets discuss 2 approaches for this problem.

Solution
Method 1 (Simple)
Following is a simple algorithm where we first find the middle node of list and make it root of the tree to be constructed.
```1) Get the Middle of the linked list and make it root.
2) Recursively do same for left half and right half.
a) Get the middle of left half and make it left child of the root
created in step 1.
b) Get the middle of right half and make it right child of the
root created in step 1.

```
Time complexity: O(nLogn) where n is the number of nodes in Linked List.This is because each level of recursive call requires a total of n/2 traversal steps in the list, and there are total log(n) number of levels.

Method 2 (Tricky)
The method 1 constructs the tree from root to leave, i.e. top down approach.

Now lets follow bottom up approach. In this method, we construct from leaves to root. The idea is to insert nodes in BST in the same order as the appear in Linked List, so that the tree can be constructed in O(n) time complexity. We first count the number of nodes in the given Linked List. Let the count be n. After counting nodes, we take left n/2 nodes and recursively construct the left subtree. After left subtree is constructed, we allocate memory for root and link the left subtree with root. Finally, we recursively construct the right subtree and link it with root.
```public TreeNode sortedListToBST(ListNode head,int start, int end) {
if(start>end) return NULL;
int mid = (start+end)/2;
TreeNode leftChild = sortedListToBST(list, start, mid-1);
TreeNode parent = new TreeNode();
if(parent==null)
System.out.println("Memory error");
parent.setData(list.getData());
parent.setLeft(leftChild);
list = list.getNext();
parent.sertRight(sortedListToBST(list,mid+1,end));
return parent;
}
//method caller