首页
题库
面试
求职
学习
竞赛
More+
所有博客
搜索面经/职位/试题/公司
搜索
我要招人
去企业版
登录 / 注册
首页
>
试题广场
>
有序链表变成二叉搜索树
[编程题]有序链表变成二叉搜索树
热度指数:20352
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32M,其他语言64M
算法知识视频讲解
给定一个单链表,其中的元素按升序排序,请将它转化成平衡二叉搜索树(BST)
示例1
输入
{-1,0,1,2}
输出
{1,0,2,-1}
说明:本题目包含复杂数据结构TreeNode、ListNode,
点此查看相关信息
马上挑战
算法知识视频讲解
提交运行
算法知识视频讲解
添加笔记
求解答(0)
邀请回答
收藏(111)
分享
提交结果有问题?
81个回答
2篇题解
开通博客
华科不平凡
发表于 2020-08-21 20:49:38
思路和数组差不多,只是链表需要通过快慢指针找到中间节点: 根据题目示例,如果节点个数为偶数个,应该将中间偏右的那个作为根节点; 不需要断链,如果断链反而麻烦很多。 总结一下如何定位中间偏右(偶数个节点数)的节点以及如何定位中间偏左的节点: 中间偏右:循环条件为!fast &&
展开全文
O-Precedence
发表于 2021-09-08 11:03:08
其实(fast!=null&&fast.next!=null)之前一直写成了(fast.next!=null&&fast.next.next!=null),结果就不对了。 import java.util.*; /* * public class TreeNode
展开全文
问题信息
链表
树
难度:
81条回答
111收藏
19311浏览
热门推荐
通过挑战的用户
查看代码
牛客38441...
2022-09-14 17:54:50
=120191...
2022-09-14 15:27:13
牛客61312...
2022-09-11 16:11:06
牛客63727...
2022-09-02 11:12:37
牛客45975...
2022-08-28 20:28:43
相关试题
未来工作城市的选择是怎样的?
通用能力
评论
(1)
你说在销售运营这个岗位上会涉及到一...
评论
(1)
“乔布斯不做调查,张小龙不看数据。...
用户研究
评论
(1)
相关性分析有哪些?
评论
(1)
如何检验聚类分析结果
评论
(1)
扫描二维码,关注牛客网
意见反馈
下载牛客APP,随时随地刷题
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * } */ /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param head ListNode类 * @return TreeNode类 */ public TreeNode sortedListToBST (ListNode head) { // write code here } }
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ /** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param head ListNode类 * @return TreeNode类 */ TreeNode* sortedListToBST(ListNode* head) { // write code here } };
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # # @param head ListNode类 # @return TreeNode类 # class Solution: def sortedListToBST(self , head ): # write code here
/* * function TreeNode(x) { * this.val = x; * this.left = null; * this.right = null; * } */ /* * function ListNode(x){ * this.val = x; * this.next = null; * } */ /** * * @param head ListNode类 * @return TreeNode类 */ function sortedListToBST( head ) { // write code here } module.exports = { sortedListToBST : sortedListToBST };
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # # @param head ListNode类 # @return TreeNode类 # class Solution: def sortedListToBST(self , head ): # write code here
package main import . "nc_tools" /* * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ /* * type ListNode struct{ * Val int * Next *ListNode * } */ /** * * @param head ListNode类 * @return TreeNode类 */ func sortedListToBST( head *ListNode ) *TreeNode { // write code here }
{-1,0,1,2}
{1,0,2,-1}