One, Title Description
Given a singly linked list where elements are sorted in ascending order,
convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree
in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted linked list: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
Second, the problem solution
Method one: the list into an array
The method and the ordered array into a binary search tree is the same, using divide and conquer idea, constantly compression range.
public TreeNode sortedListToBST(ListNode head) {
List<Integer> nums = new ArrayList<>();
while (head != null) {
nums.add(head.val);
head = head.next;
}
return dfs(nums, 0, nums.size());
}
TreeNode dfs(List<Integer> nums, int l, int r) {
if (l == r) {
return null;
}
int mid = (l + r) >>> 1;
TreeNode root = new TreeNode(nums.get(mid));
root.left = dfs(nums, l, mid);
root.right = dfs(nums, mid+1, r);
return root;
}
Complexity Analysis
- time complexity: ,
- Space complexity: ,
Method two: Find the list of intermediate node
Core logic: Looking central node list. Then recursively constructed binary search tree.
- slow walk one step, fast take two steps, fast is empty, slow to reach the center of the list.
public TreeNode sortedListToBST(ListNode head) {
if (head == null)
return null;
return dfs(head, null);
}
private TreeNode dfs(ListNode l, ListNode r) {
if (l == r)
return null;
ListNode slow = l;
ListNode fast = l;
while (fast != r && fast.next != r) {
slow = slow.next;
fast = fast.next.next;
}
TreeNode root = new TreeNode(slow.val);
root.left = dfs(l, slow);
root.right = dfs(slow.next, r);
return root;
}
Complexity Analysis
- time complexity: , for n nodes in the linked list, need to log (n) time to find its center nodes.
- Space complexity: , the height of the binary search tree is 。