题目链接 : https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree/

题目描述:

给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

示例:

给定的有序链表: [-10, -3, 0, 5, 9],

一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:

      0
/ \
-3 9
/ /
-10 5 来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路:

与上一题108. 将有序数组转换为二叉搜索树,还是找中点

但是这个是链表找中点,所以我们用快慢指针!

代码:

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
def findmid(head, tail):
slow = head
fast = head
while fast != tail and fast.next!= tail :
slow = slow.next
fast = fast.next.next
return slow def helper(head, tail):
if head == tail: return
node = findmid(head, tail)
root = TreeNode(node.val)
root.left = helper(head, node)
root.right = helper(node.next, tail)
return root return helper(head, None)

java

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode sortedListToBST(ListNode head) {
if (head == null) return null;
return helper(head, null); } private TreeNode helper(ListNode head, ListNode tail) {
if (head == tail) return null;
// mid
ListNode slow = head;
ListNode fast = head;
while (fast != tail && fast.next != tail) {
slow = slow.next;
fast = fast.next.next;
}
TreeNode root = new TreeNode(slow.val);
root.left = helper(head, slow);
root.right = helper(slow.next, tail);
return root;
}
}

最新文章

  1. 转】C#接口-显式接口和隐式接口的实现
  2. 关于xfce桌面程序启动失败
  3. ORA-04021 timeout occurred while waiting to lock object
  4. windows下使用批处理脚本实现多个版本的JDK切换
  5. iOS-NSDate 相差 8 小时
  6. jsp页面变量作用域问题
  7. bootstrap实现手风琴功能(树形列表)
  8. Android下的Linux指令集
  9. PHP删除数组中特定元素
  10. js库编写的环境和准备工作
  11. lnmp源码安装以及简单配置
  12. Andriod布局之LinearLayout
  13. Flask web开发 处理POST请求(登录案例)
  14. Spring Security教程系列(一)基础篇-2
  15. Spring思维导图(一)
  16. iOS开发-添加圆角效果高效实现
  17. zookeeper图形化的客户端工具
  18. Async 详解
  19. 微信小程序制作家庭记账本之三
  20. JavaScript动态加载资源

热门文章

  1. MongoDB学习笔记 1.1
  2. Ajax请求参数到一个URL包含下划线或者v(_、v)
  3. spring cloud-1
  4. 页面渲染机制(一、DOM和CSSOM树的构建)
  5. Mybatis-Plus和Mybatis的区别
  6. [BZOJ1059]:[ZJOI2007]矩阵游戏(二分图匹配)
  7. rollup的学习
  8. Java 使用反射给属性赋值
  9. kafka原理和实践
  10. Windows下启动.Net Core程序脚本