您的位置:首页 > 其它

Convert Sorted List to Binary Search Tree

2015-12-19 06:23 309 查看
题目:

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

解法一:双节点

public TreeNode sortedListToBST(ListNode head) {
if(head == null)
return null;
ListNode fast = head;
ListNode slow = head;
ListNode prev =null;
while(fast != null && fast.next != null)
{
fast = fast.next.next;
prev =slow;
slow=slow.next;
}
TreeNode root = new TreeNode(slow.val);
if(prev != null)
prev.next = null; //断掉前面序列和中点之间的联系,不然recursion没法找到前面序列的中点
else
head  = null;

root.left = sortedListToBST(head);
root.right = sortedListToBST(slow.next);
return root;
}


reference:https://leetcode.com/discuss/58428/recursive-construction-using-slow-fast-traversal-linked-list

解法二:

public class Solution {
private ListNode current;

private int getListLength(ListNode head) {
int size = 0;

while (head != null) {
size++;
head = head.next;
}

return size;
}

public TreeNode sortedListToBST(ListNode head) {
int size;

current = head;
size = getListLength(head);

return sortedListToBSTHelper(size);
}

public TreeNode sortedListToBSTHelper(int size) {
if (size <= 0) {
return null;
}

TreeNode left = sortedListToBSTHelper(size / 2);
TreeNode root = new TreeNode(current.val);
current = current.next;
TreeNode right = sortedListToBSTHelper(size - 1 - size / 2);

root.left = left;
root.right = right;

return root;
}
}


reference:http://www.jiuzhang.com/solutions/convert-sorted-list-to-binary-search-tree/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: