- 109. Convert Sorted List to Bina
- 109. Convert Sorted List to Bina
- 109. Convert Sorted List to Bina
- 109. Convert Sorted List to Bina
- 109. Convert Sorted List to Bina
- 109. Convert Sorted List to Bina
- 109. Convert Sorted List to Bina
- 109. Convert Sorted List to Bina
- 109. Convert Sorted List to Bina
- 109. Convert Sorted List to Bina
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
由于需要平衡树,所以取中点作为根,两边为左右子树,依次递归下去
var sortedListToBST = function(head) {
if(head===null) return null;
return toBST(head,null);
function toBST(head, tail){
var slow = head;
var fast = head;
if(head===tail) return null;
while(fast!==tail&&fast.next!==tail){
fast = fast.next.next;
slow = slow.next;
}
var thead = new TreeNode(slow.val);
thead.left = toBST(head,slow);
thead.right = toBST(slow.next,tail);
return thead;
}
};
网友评论