How to convert a sorted list to a binary tree

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 O(n)O(n).

Method

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.

Example

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 linked list:

%0 node_1 1 node_1564744979451 2 node_1->node_1564744979451 node_1564744912919 3 node_1564744979451->node_1564744912919 node_1564744945966 4 node_1564744912919->node_1564744945966 node_1564744901302 5 node_1564744945966->node_1564744901302 node_1564745552214 6 node_1564744901302->node_1564745552214 node_1564745474095 7 node_1564745552214->node_1564745474095

The converted binary tree:

%0 node_1 4 node_1564745454796 2 node_1->node_1564745454796 node_1564745453945 6 node_1->node_1564745453945 node_1564745513249 1 node_1564745454796->node_1564745513249 node_1564745544123 3 node_1564745454796->node_1564745544123 node_1564745511471 5 node_1564745453945->node_1564745511471 node_1564745469108 7 node_1564745453945->node_1564745469108

Implementation

The code below implements the method above.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved