Given a singly linked list of integers increasing order, construct a balanced binary tree that is also a BST, containing the same data members as the linked list.
Examples:
Input: Linked List : 1->2->3 👁 Image Output: 2 1 3 Explanation: The BST formed using elements of the linked list is - 👁 Image Hence, the preorder traversal of this tree is 2 1 3.
[Naive Approach] Using an Array - O(n) time and O(n) space
The core idea involves converting the linked list into an array. Then, the middle element of this array is used as the root, recursively building a balanced BST.
Output
4 2 1 3 6 5 7
[Expected Approach] In-Order Traversal - O(n) time and O(log n) space
This approach mimics an in-order traversal to construct the tree directly from the linked list. This is achieved by counting the nodes and then recursively building the left subtree, the root, and the right subtree.