leetcode 【 Convert Sorted List to Binary Search Tree 】python 实现

题目

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

 

代码:oj测试通过 Runtime: 178 ms

复制代码
 1 # Definition for a  binary tree node
 2 # class TreeNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 #
 8 # Definition for singly-linked list.
 9 # class ListNode:
10 #     def __init__(self, x):
11 #         self.val = x
12 #         self.next = None
13 
14 class Solution:
15     # @param head, a list node
16     # @return a tree node
17     def sortedListToBST(self, head):
18         # special case frist
19         if head is None:
20             return None
21         if head.next is None:
22             return TreeNode(head.val)
23         # slow point & fast point trick to divide the list    
24         slow = ListNode(0)
25         fast = ListNode(0)
26         slow.next = head
27         fast.next = head
28         while fast.next is not None and fast.next.next is not None:
29             slow = slow.next
30             fast = fast.next.next
31         left = head
32         right = slow.next.next
33         root = TreeNode(slow.next.val)
34         slow.next.next = None # cut the connection bewteen right child tree and root TreeNode
35         slow.next = None # cut the connection between left child tree and root TreeNode
36         root.left = self.sortedListToBST(left)
37         root.right = self.sortedListToBST(right)
38         return root
复制代码

思路

binary search tree 是什么先搞清楚

由于是有序链表,所以可以采用递归的思路,自顶向下建树。

1. 每次将链表的中间节点提出来;链表中间节点之前的部分作为左子树继续递归;链表中间节点之后的部分作为右子树继续递归。

2. 停止递归调用的条件是传递过去的head为空(某叶子节点为空)或者只有一个ListNode(到某叶子节点了)。

找链表中间节点的时候利用快慢指针的技巧:注意,因为前面的special case已经将传进来为空链表和长度为1的链表都处理了,所以快慢指针的时候需要判断一下从最短长度为2的链表的处理逻辑。之前的代码在while循环中只判断了fast.next.next is not None就忽略了链表长度为2的case,因此补上了一个fast.next is not None的case,修改过一次就AC了。

网上还有一种思路,只需要走一次链表就可以完成转换,利用的是自底向上建树。下面这个日志中有说明,留着以后去看看。

http://blog.csdn.net/nandawys/article/details/9125233

posted on   承续缘  阅读(419)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示