109. Convert Sorted List to Binary Search Tree
Solution1: use 108, convert to list then do the same.
T: O(2n)
class Solution {
public TreeNode sortedListToBST(ListNode head) {
List<Integer> list = new ArrayList<>();
ListNode temp = head;
while (temp != null) {
list.add(temp.val);
temp = temp.next;
}
return dfs(list, 0, list.size()-1);
}
private TreeNode dfs(List<Integer> list, int left, int right) {
if (left > right) {
return null;
}
int mid = (left + right)/2;
TreeNode root = new TreeNode(list.get(mid));
root.left = dfs(list, left, mid-1);
root.right = dfs(list, mid + 1, right);
return root;
}
}
solution 2: use slow fast pointer to find mid
and dfs(head, null) to build BS tree
slower than solution1, because needs to find mid every time...
Solution3: directly uses inorder
T: O(n)
improved Solution 3
use a class Wrapper to avoid using global variable:
Last updated
Was this helpful?