LeetCode解题之Convert Sorted List to Binary Search Tree
原题
给定一个升序的单向链表。将它转化为高度平衡的二叉搜索树。
注意点:
- 同一个序列转化成的二叉搜索树可能有多种
样例:
输入: nums = 1->2->3
输出:
2
/ 1 3
解题思路
这题就是 Convert Sorted Array to Binary Search Tree 的升级版,能够先把链表转化为列表再解答。
假设直接用链表解决的话。能够看出链表的特点是从头到尾依次遍历,由于是递增的,所以也就是从小到大依次遍历。而二叉所搜树的中序遍历的结果就是一个递增的序列,所以仅仅要依照树的中序遍历的方式来构造就可以。
AC源代码
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def sortedListToBST(self, head):
"""
:type head: ListNode
:rtype: TreeNode
"""
node, length = head, 0
while node:
node = node.next
length += 1
self.curr = head
return self._sortedListToBST(0, length - 1)
def _sortedListToBST(self, left, right):
if left > right:
return None
mid = (left + right) // 2
left = self._sortedListToBST(left, mid - 1)
root = TreeNode(self.curr.val)
root.left = left
self.curr = self.curr.next
root.right = self._sortedListToBST(mid + 1, right)
return root
if __name__ == "__main__":
None
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源代码。