
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
不能将linked list转换成arraylist,会超时。思路:快慢指针。
ListNode cutAtMid(ListNode head) {
if (head == null) {
return null;
}
ListNode fast = head;
ListNode slow = head;
ListNode pslow = head;
while (fast != null && fast.next != null) {
pslow = slow;
slow = slow.next;
fast = fast.next.next;
}
pslow.next = null;
return slow;
}
public TreeNode sortedListToBST(ListNode head) {
if (head == null) {
return null;
}
if (head.next == null) {
return new TreeNode(head.val);
}
ListNode mid = cutAtMid(head);
TreeNode root = new TreeNode(mid.val);
root.left = sortedListToBST(head);
root.right = sortedListToBST(mid.next);
return root;
}原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。