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 = rightclass Solution:def sortedListToBST(self, head: ListNode) -> TreeNode:self.height = collections.defaultdict(int)def getHeight(node):if not node:return -1return self.height[node]def updateHeight(node):self.height[node] = max(getHeight(node.left), getHeight(node.right)) + 1def leftRotation(root):newRoot = root.rightroot.right = newRoot.leftnewRoot.left = rootupdateHeight(newRoot)updateHeight(root)return newRootdef 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 rootres = Nonewhile head:res = insert(res, head.val)head = head.nextreturn res
题目分析
AVL的构建,很标准的一个流程。
注意updateHeight,别忘了,rotation之后也要更新两个height。
其它解法
这道题,分治,加上一点链表操作的trick,应该写的更加简单,而且效率也更高。
class Solution:def sortedListToBST(self, head: ListNode) -> TreeNode:def f(l, r):if l == r:return Noneslow, fast = l, lwhile fast != r and fast.next != r:slow = slow.nextfast = fast.next.nextroot = TreeNode(slow.val)root.left = f(l, slow)root.right = f(slow.next, r)return rootreturn f(head, None)
这个解法也可以写成迭代的,不过没有递归来的清晰。
