https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
这道题用AVL-tree做的确有一点夸张,而且更慢,但是权当是复习一下AVL-Tree的构建了。
个人解答
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
self.height = collections.defaultdict(int)
def getHeight(node):
if not node:
return -1
return self.height[node]
def updateHeight(node):
self.height[node] = max(getHeight(node.left), getHeight(node.right)) + 1
def leftRotation(root):
newRoot = root.right
root.right = newRoot.left
newRoot.left = root
updateHeight(newRoot)
updateHeight(root)
return newRoot
def insert(root, val):
if not root:
return TreeNode(val)
root.right = insert(root.right, val)
if getHeight(root.right) - getHeight(root.left) > 1:
root = leftRotation(root)
updateHeight(root)
return root
res = None
while head:
res = insert(res, head.val)
head = head.next
return res
题目分析
AVL的构建,很标准的一个流程。
注意updateHeight,别忘了,rotation之后也要更新两个height。
其它解法
这道题,分治,加上一点链表操作的trick,应该写的更加简单,而且效率也更高。
class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
def f(l, r):
if l == r:
return None
slow, fast = l, l
while fast != r and fast.next != r:
slow = slow.next
fast = fast.next.next
root = TreeNode(slow.val)
root.left = f(l, slow)
root.right = f(slow.next, r)
return root
return f(head, None)
这个解法也可以写成迭代的,不过没有递归来的清晰。