Convert Sorted List to Binary Search Tree

·

2 min read

Problem Statement

Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height-balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differs by more than 1.

Example:-

Input: head = [-10,-3,0,5,9]

Output: [0,-3,9,-10,null,5]

Explanation: One possible answer is [0,-3,9,-10, null,5], which represents the shown height-balanced BST.

Approach:-

We first find the middle node of the list and make it the root of the tree to be constructed.

Steps:-

1) Get the Middle of the linked list and make it root.

2) Recursively do the same for the left half and right half.

  • Get the middle of the left half and make it left child of the root created in step 1.

  • Get the middle of the right half and make it the right child of the root created in step 1.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head, ListNode* tail)
    {
        if(head==tail) return NULL;
        if(head->next==tail) 
        {
            TreeNode* root=new TreeNode(head->val);
            return root;
        }
        ListNode* mid=head, *temp=head;
        while(temp!=tail && temp->next!=tail)
        {
            mid=mid->next;
            temp=temp->next->next;
        }
        TreeNode* root=new TreeNode(mid->val);
        root->left=sortedListToBST(head,mid);
        root->right=sortedListToBST(mid->next,tail);
        return root;
    }
    TreeNode* sortedListToBST(ListNode* head) {
        return sortedListToBST(head,NULL);
    }
};