109. Convert Sorted List to Binary Search Tree
Solution1: use 108, convert to list then do the same.
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
Solution3: directly uses inorder
improved Solution 3
Last updated