标签:leetcode
https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
http://fisherlei.blogspot.com/2013/01/leetcode-convert-sorted-list-to-binary.html
http://blog.csdn.net/worldwindjp/article/details/39722643
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; next = null; }
* }
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
// Option A:
TreeNode root = buildTop2Buttom(head, null);
return root;
}
//////////////////////////
// Option A: Top to bottom
//
// Unlike sorted array, no random access.
// But we still can follow the same strategy that:
// Given head, find the mid.
// O(n log n)
private TreeNode buildTop2Buttom(ListNode start, ListNode end)
{
if (start == null || start == end)
return null;
if (start.next == end)
return new TreeNode(start.val);
ListNode mid = findMid(start, end);
TreeNode root = new TreeNode(mid.val);
root.left = buildTop2Buttom(start, mid);
root.right = buildTop2Buttom(mid.next, end);
return root;
}
// Find the mid node from ‘start‘(inclusive) to ‘end‘(exclusive)
private ListNode findMid(ListNode start, ListNode end)
{
ListNode toReturn = null;
ListNode s1 = start;
ListNode s2 = start;
while (s2 != null && s2 != end)
{
toReturn = s1;
s1 = s1.next;
s2 = s2.next;
if (s2 == null || s2 == end)
s2 = null;
else
s2 = s2.next;
}
return toReturn;
}
}[LeetCode]109 Convert Sorted List to Binary Search Tree
标签:leetcode
原文地址:http://7371901.blog.51cto.com/7361901/1598375