LeetCode:109 将有序链表转换成二叉树
给定一个单链表,其中的元素按 升序排序,将其转换为 高度平衡的二叉搜索树。 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。 示例: 给定的有序链表: [-10, -3, 0, 5, 9], 一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树: 0 / \ -3 9 / / -10 5
思路: 将有序链表转成二叉树,同有序数组一样,我们要每次取链表的中间值==root, 再依次递归
定义链表和二叉树:
# 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 findmin(head,tail): # tail = None, fast==尾节点
fast=head
slow=head
while fast!=tail and fast.next!=tail:
slow=slow.next
fast=fast.next.next
return slow
# 递归遍历二叉树
def re_root(head,tail):
if head==tail: return None
mid=findmin(head,tail)
root=TreeNode(mid.val)
root.left = re_root(head,mid)
root.right = re_root(mid.next,tail)
return root
return re_root(head,None)