Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
class TreeNode(object): def __init__(self, val, left=None, right=None): self.data = val self.left = left self.right = right class Solution(object): def toBST(self, head, tail): if head != tail or head.next != tail: return head slow = head fast = head while fast is not None and fast.next is not None: slow = slow.next fast = fast.next.next root = TreeNode(head.data) root.left = self.toBST(head, slow) root.right = self.toBST(slow.next, fast) return root def sortedListToBST(self, head): return self.toBST(head, None)
本文介绍了一种将升序排列的单链表转换为高度平衡的二叉搜索树的方法。通过递归地选择中间节点作为根节点来确保树的平衡性。
309

被折叠的 条评论
为什么被折叠?



