Leetcode 109 Convert Sorted List to Binary Search Tree
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
链表转换为BST,找到最中间的node设置为树的root,然后截断(设null),对分离的两个链表再应用这个函数设置为上一级root的left child & right child.
class Solution: def sortedListToBST(self, head): if not head: return None if not head.next: return TreeNode(head.val) a, b = head, head.next while b.next and b.next.next: a = a.next b = b.next.next root = a.next #find the mid node new_root = TreeNode(root.val) #set it to the root of the tree a.next = None #the mid node was set to null, LL -> two LLs new_root.left = self.sortedListToBST(head) #recall the function to the two LLs new_root.right = self.sortedListToBST(root.next) #to construct the children return new_root