Convert Sorted List to Binary Search Tree - Complete Solution Guide
Convert Sorted List to Binary Search Tree is LeetCode problem 109, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
Given the head of a singly linked list where elements are sorted in ascending order , convert it to a height-balanced binary search tree . Example 1: 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. Example 2: Input: head = [] Output: [] Constraints: The number of nodes in head is in the range [0, 2 * 10 4 ] . -10 5 <= Node.val <= 10 5
Detailed Explanation
The problem asks us to convert a sorted singly linked list into a height-balanced Binary Search Tree (BST). A height-balanced BST is a binary tree where the height difference between the left and right subtrees of every node is no more than one. The input is the head of a sorted linked list, and the output is the root of the height-balanced BST. The list is sorted in ascending order, which is crucial for building a BST.
Solution Approach
The provided solution uses a recursive approach combined with a 'global' pointer to the head of the linked list to mimic an inorder traversal while constructing the BST. First, the length of the list is computed. Then, a recursive helper function `build_tree` is defined, which takes the left and right boundaries of the sublist as input. In each recursive call, the middle element of the sublist is chosen as the root. The left and right subtrees are built recursively. A crucial optimization is maintaining a global `head_node` pointer that initially points to the head of the list. Before processing the right subtree, this `head_node` pointer is advanced to simulate the inorder traversal.
Step-by-Step Algorithm
- Step 1: Calculate the length of the linked list. This is done by iterating through the list and incrementing a counter.
- Step 2: Initialize a 'global' `head_node` pointer to the head of the linked list. This pointer will be used to traverse the list during the tree construction.
- Step 3: Define a recursive helper function `build_tree(left, right)` that takes two integers `left` and `right` representing the start and end indices of the current sublist.
- Step 4: In `build_tree`, check the base case: if `left > right`, return `None` (or `nullptr` in C++ or `NULL` in C or null in Java) as there's nothing to process.
- Step 5: Calculate the middle index `mid = left + (right - left) // 2`. This avoids potential integer overflow.
- Step 6: Recursively build the left subtree by calling `build_tree(left, mid - 1)`.
- Step 7: Create a new `TreeNode` with the value of the current `head_node`. Assign the left subtree returned in Step 6 as the left child of the new node.
- Step 8: Advance the `head_node` pointer to its next node in the linked list. This simulates the inorder traversal.
- Step 9: Recursively build the right subtree by calling `build_tree(mid + 1, right)`. Assign the result as the right child of the current node.
- Step 10: Return the current `TreeNode` (root).
Key Insights
- Insight 1: The inorder traversal of a BST yields a sorted sequence. Since we have a sorted linked list, we can simulate an inorder traversal during the tree construction process.
- Insight 2: To build a balanced BST, the middle element of the sorted list should be the root. Recursively constructing the left and right subtrees using the elements before and after the middle element will result in a balanced tree.
- Insight 3: The key to solving this problem efficiently is avoiding repeatedly traversing the linked list to find the middle element in each recursive call. We can maintain a global pointer to the head of the linked list and advance it as we build the tree, simulating an inorder traversal.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(log(n))
Topics
This problem involves: Linked List, Divide and Conquer, Tree, Binary Search Tree, Binary Tree.
Companies
Asked at: Lyft, Meta, Uber, Zenefits.