leetcode: Convert Sorted List to Binary Search Tree
If you have solved the previous problem, then it can be done by first convert the list into a vector and then do the same thing as the previous problem does. The interesting way is to do it on the list itself and almost O(1) space used.
The idea is thus:
- first, get length of the list
- recursively build left subtree bottom up
- create current root and move list pointer to next element
- recursively build right subtree bottom up
- return the root
My orignal solution uses an instance memeber ListNode* cur
to remember current position of list. but I see some guys using reference to ListNode pointer to finish the job which I think more elegant.
1 | class Solution { |
PS: I believe the space complexity is O(lgN) due to stack usage.