关注
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;
// }
}
查看原帖
点赞 评论
相关推荐
点赞 评论 收藏
分享
点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 开工第一帖 #
13036次浏览 274人参与
# 携程求职进展汇总 #
882650次浏览 5795人参与
# xx岗简历求拷打 #
4156次浏览 48人参与
# 工作不开心辞职是唯一出路吗 #
8062次浏览 30人参与
# 有转正机会的小厂实习值得去吗? #
6031次浏览 73人参与
# 掌握什么AI技能,会为你的求职大大加分 #
4412次浏览 201人参与
# 实习期间如何提升留用概率? #
241488次浏览 1824人参与
# 为什么国企只招应届生 #
238772次浏览 1301人参与
# 参加完秋招的机械人,还参加春招吗? #
111107次浏览 709人参与
# 哪些公司开春招了? #
32810次浏览 204人参与
# 秋招你经历过哪些无语的事 #
101361次浏览 597人参与
# 金三银四,你有感觉到吗 #
691708次浏览 6088人参与
# 毕业季等于分手季吗 #
54903次浏览 654人参与
# 牛客租房专区 #
160252次浏览 1922人参与
# 联想求职进展汇总 #
335062次浏览 2220人参与
# 牛友投递互助,不漏校招机会 #
439123次浏览 5243人参与
# 正在春招的你,也参与了去年秋招吗? #
353087次浏览 2597人参与
# 你最讨厌面试被问什么 #
6262次浏览 81人参与
# 非技术er求职现状 #
139165次浏览 821人参与
# 你觉得今年春招回暖了吗 #
931309次浏览 7233人参与