您的位置:首页 > 编程语言 > Python开发

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

2015-01-11 20:06 495 查看
题目

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

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

# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
# @param head, a list node
# @return a tree node
def sortedListToBST(self, head):
# special case frist
if head is None:
return None
if head.next is None:
return TreeNode(head.val)
# slow point & fast point trick to divide the list
slow = ListNode(0)
fast = ListNode(0)
slow.next = head
fast.next = head
while fast.next is not None and fast.next.next is not None:
slow = slow.next
fast = fast.next.next
left = head
right = slow.next.next
root = TreeNode(slow.next.val)
slow.next.next = None # cut the connection bewteen right child tree and root TreeNode
slow.next = None # cut the connection between left child tree and root TreeNode
root.left = self.sortedListToBST(left)
root.right = self.sortedListToBST(right)
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: