Description:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Solution:
每次dfs记录开通和结束的节点下标,从而计算出他的长度。根据长度进行构造,和前面几道题目一样,算出中心位置的下标,取出val作为子节点。再往下递归。
import java.util.*;
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
int len = 0;
ListNode temp = head;
while (temp != null) {
len++;
temp = temp.next;
}
return dfs(head, 0, len - 1);
}
TreeNode dfs(ListNode head, int start, int end) {
if (start > end)
return null;
int mid = (start + end) / 2;
ListNode temp = head;
for (int i = start; i < mid; i++)
temp = temp.next;
TreeNode root = new TreeNode(temp.val);
root.left = dfs(head, start, mid - 1);
root.right = dfs(temp.next, mid + 1, end);
return root;
}
}