Convert Sorted List to Binary Search Tree
来源:互联网 发布:sqlserver 商业智能 编辑:程序博客网 时间:2024/06/02 05:32
soln recursive 解法
public class Solution {
static ListNode head; // must add thispublic TreeNode sortedListToBST(ListNode head) {
if(head==null) return null;
this.head=head;
ListNode t=head;
int len=0;
while(t!=null){
len++;
t=t.next;
}
if(len==1) {
TreeNode rootn = new TreeNode(head.val);
return rootn;
}
return sortedListToBST(0,len-1,head);
}
private TreeNode sortedListToBST(int start, int end, ListNode node) {
if(start>end) return null;
ListNode tmp = node;
int mid = start +(end-start)/2;
for(int i=start;i<mid;i++){
tmp=tmp.next;
}
TreeNode root=new TreeNode(tmp.val);
TreeNode left = sortedListToBST(start,mid-1,node);
root.left = left;
TreeNode right = sortedListToBST(mid+1,end,tmp.next);
root.right = right;
return root;
}
}
0 0
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- convert sorted list to binary search tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- 回答师兄for循环的问题
- ESRI.ArcGIS.AnalysisTools 与 ESRI.ArcGIS.Geoprocessor
- bochs 编译安装
- 基于bootstrap的 按钮-隐藏 案例
- 日经社説 20150122 経営力を高め好循環つくれ
- Convert Sorted List to Binary Search Tree
- 利用织梦dedecms单页功能制作Sitemap.xml地图
- 日经社説 20150122 理想論のオバマ教書で米政治は動くか
- scrum training
- linux 修改文件夹及文件拥有者与群组(1)
- SDUT 1595 选夫婿2
- git默认拒绝了push操作
- 深入 Lucene 索引机制-学习笔记1
- 社説 20150122 訪日客急増 観光立国へ弾みをつけたい