关注
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;
// }
}
查看原帖
点赞 评论
相关推荐
02-13 18:45
山东大学 C++ 点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 牛客新年AI问运 #
2939次浏览 75人参与
# 刚工作,应该先搞钱or搞成长? #
20792次浏览 159人参与
# 牛客AI体验站 #
15557次浏览 276人参与
# 你觉得第一学历对求职有影响吗? #
229937次浏览 1266人参与
# 找工作中的小确幸 #
80377次浏览 448人参与
# 实习在多还是在精 #
82748次浏览 509人参与
# 你觉得技术面多长时间合理? #
168076次浏览 1170人参与
# 月薪多少能在一线城市生存 #
136391次浏览 898人参与
# 牛友的春节生活 #
11602次浏览 223人参与
# 选了这个offer,你有没有后悔? #
738444次浏览 4472人参与
# 备战春招/暑实,现在应该做什么? #
7773次浏览 203人参与
# 从夯到拉,锐评职场mentor #
7598次浏览 109人参与
# 实习到现在,你最困惑的一个问题 #
6771次浏览 165人参与
# 春招什么时候投? #
13057次浏览 208人参与
# 电网笔面经互助 #
59666次浏览 476人参与
# 制造业的秋招小结 #
143348次浏览 2089人参与
# 秋招踩过的“雷”,希望你别再踩 #
185664次浏览 1683人参与
# 你有哪些缓解焦虑的方法? #
51149次浏览 906人参与
# 春节提前走,你用什么理由请假? #
13345次浏览 288人参与
# 距离春招还有一个月,你现在是什么开局? #
9268次浏览 132人参与