A sorted linked list is used to construct a binary tree from the leaves to the root. The idea is to insert nodes in a binary tree in the same order as they appear in the linked list so that the tree can be constructed with the time complexity of .
The number of nodes in the linked list are counted and set equal to n. First, the middle node is set as the root (always). Then, the left subtree is constructed recursively, using the left n/2 nodes, and connected with the root at the end. The right subtree is similarly constructed and connected to the root.
While constructing the BST, we keep moving the list head pointer to the next node so that we have the appropriate pointer in each recursive call.
Suppose the following linked list needs to be converted into a binary tree. The following illustrations make use of the above-mentioned method to create a binary tree.
The code below implements the method above.
Free Resources