# Can someone do this in place with O(n) time?

• I used an extra array to do this, it has O(n) storage and time.
But I have a feeling that this one can be solved with O(1) memory, of course, linear time.

• Without considering the stack of recursive function calls, constructing the BST from bottom up is O(N) time and O(1) space.

• I doubt it. If you don't use an extra array which can access it's middle in constant time, how you build the tree recursively in O(n) time? Please briefly describe your tree building strategy.

• The key is to create the nodes by the list's order in a bottom-up fashion. Read this article:
Convert Sorted List to Balanced Binary Search Tree (BST) for an in-depth analysis and solution for this problem.

• You can construct from bottom up then no need to fetch the node to an array. Just like the other answer by 1337c0d3r said.

• Here is my python code with the same idea as others said.

``````class Solution:
# @param head, a list node
# @return a tree node
return None
N = 0
while cur:
N += 1
cur = cur.next
return A[0]

if N == 1:
root = TreeNode(l[1].val)
root.left = l[0]
if (N-1)/2:
r = self.listToBST(l[1].next, (N-1)/2)
root.right = r[0]
return [root, r[1]]
else:
return [root, l[1].next]``````

• Thanks for sharing!

• The above code is so elegant but tricky. To understand the code, u can read this one http://www.geeksforgeeks.org/sorted-linked-list-to-balanced-bst/ which contain a better explanation.

• Both these solutions are not really O(1) in terms of space complexity. Considering the recursive call stack, they are O(logn).

• The solutions are not O(1) space, not only because of the recursion but because we're creating n nodes in memory for each new tree node

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.