【小熊刷题】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; } }
相关文章推荐
- SpringMVC的Ajax提交
- Spring之Aop与Ioc
- github开源php项目
- empty(), is_null(), isset()(区别)
- Majority Element II
- 愿少时无遗憾留低 愿余生有艺术伴随
- Linux自行学习命令1
- 安装启动 Supervisor
- [ACdream 1211 Reactor Cooling]无源无汇有上下界的可行流
- fontcreator 预览放大
- @RestController实现spring自己风格的rest的webservice(不用jax-rs包)
- [LeetCode#44]Wildcard Matching
- php大力力 [019节]php分页类的学习
- mockito测试入门
- apache反向代理 负载均衡
- 在spring中构建基于jax-RS(即rest风格)的webservice
- tomcat的temp文件夹不要随便删除
- 一分钟搭建个人详情界面
- MacType最强配置图解
- android sdk