题目链接
法一
public TreeNode sortedListToBST(ListNode head) {
if (head == null) {
return null;
}
if (head.next == null) {
return new TreeNode(head.val);
}
ListNode fast = head, slow = head, pre = null;
while (fast != null && fast.next != null) {
pre = slow;
slow = slow.next;
fast = fast.next.next;
}
pre.next = null;
ListNode rightList = slow.next;
TreeNode root = new TreeNode(slow.val);
root.left = sortedListToBST(head);
root.right = sortedListToBST(rightList);
return root;
}
本地测试
lay.showTitle(109);
Solution109 sol109 = new Solution109();
int[] nums109 = new int[]{-10, -3, 0, 5, 9};
ListNode head109 = new ListNode();
head109 = listOpt.creatListByArray(head109, nums109);
listOpt.showList(head109);
TreeNode tree109 = sol109.sortedListToBST(head109.next);
treeOpt.layerOrder(tree109);