关注
Given a singly linked list where
elements are sorted in ascending order, convert it to a height
balanced BST。提交的就是下面的,注释掉的也是对的,开始是注释掉的那种,然后改成了这种。
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head == null) return null;
if(head.next == null) return new
TreeNode(head.val);
ArrayList<Integer> list=new
ArrayList<Integer>();
while(head!=null)
{
list.add(head.val);
head=head.next;
}
return buildToBST(list,0,list.size()-1);
}
private TreeNode buildToBST(ArrayList<Integer>
list, int start, int end) {
if(end<start)return null;
int mid=(start+end+1)/2;//题目中是要求偶数时候,中间2个,选后面那个数
TreeNode root = new TreeNode(list.get(mid));
root.left=buildToBST(list,start,mid-1);
root.right=buildToBST(list,mid+1,end);
return root;
}
// public TreeNode sortedListToBST(ListNode head)
{//这个也是对的,没有上面的那个快
// if(head == null) return null;
// if(head.next == null) return new
TreeNode(head.val);
// ListNode mid = head;
// ListNode end = head;
// ListNode preMid = null;
// while (end != null && end.next != null)
{//每一次都循环快慢指针找中点
// preMid = mid;
// mid = mid.next;
// end = end.next.next;
// }
// TreeNode root = new TreeNode(mid.val);
// preMid.next = null;
// root.left = sortedListToBST(head);
// root.right = sortedListToBST(mid.next);
// return root;
// }
}
查看原帖
点赞 评论
相关推荐
09-19 13:59
门头沟学院 Java 点赞 评论 收藏
分享
面了100年面试不知...:可以跳,但要在一行深耕下去
(导那天突然这么跟我说) 点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 月薪多少能在一线城市生存 #
74835次浏览 489人参与
# 技术转行的心路历程 #
72380次浏览 740人参与
# 百度秋招 #
33781次浏览 317人参与
# 如果再来一次,你还会选择这个工作吗? #
700453次浏览 5705人参与
# 总结:哪家公司最喜欢泡池子 #
150663次浏览 542人参与
# 互联网行业现在还值得去吗 #
37464次浏览 274人参与
# 你小时候最想从事什么职业 #
133422次浏览 1982人参与
# 虾皮开奖 #
43695次浏览 206人参与
# 25届非技术实习投递记录 #
136897次浏览 1001人参与
# 滴滴歧视残疾人HR被开除 #
23414次浏览 86人参与
# 落户对你的求职选择影响有多大 #
29661次浏览 101人参与
# 你认为工作的意义是什么 #
209272次浏览 1345人参与
# 第一次找实习,我建议__ #
28995次浏览 362人参与
# 小米编程考试 #
22775次浏览 145人参与
# 从mentor身上学到了__ #
24312次浏览 420人参与
# 面试时间长是好事吗? #
109657次浏览 696人参与
# 你怎么评价今年的春招? #
144539次浏览 1394人参与
# 外出实习被同学举报 #
7039次浏览 41人参与
# 韶音科技求职进展汇总 #
62805次浏览 506人参与
# 秋招结束之后的日子 #
107189次浏览 1021人参与
# 打工人的至爽时刻or至暗时刻 #
43317次浏览 224人参与

