您的位置:首页 > 其它

【小熊刷题】Convert Sorted List to Balanced Binary Search Tree<可再复习>

2015-08-26 03:48 597 查看

Question

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

https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/

*Difficulty: Hard, Frequency: Low

Bottom-up Recursion Solution

O(n) runtime, O(log n) stack space – Bottom-up recursion

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private ListNode list;
public TreeNode sortedListToBST(ListNode head) {
int len = 0;
ListNode p = head;
while(p != null){
p = p.next;
len++;
}
list = head;
return getSubtree(0, len-1);
}

public TreeNode getSubtree(int start, int end){
if(start > end) return null; //reached the leaf's child
int mid = (start + end) / 2;
//kind of like the in-order traverse
TreeNode left = getSubtree(start, mid-1);
TreeNode node = new TreeNode(list.val);
node.left = left;
list = list.next;//very crucial steps!!
node.right = getSubtree(mid+1, end);
return node;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: