def build(start1, end2, length): if not length: return None root_val = postorder[end2] root = TreeNode(root_val) if length == 1: return root root_index = inorder.index(root_val) left_length = root_index - start1 right_length = length - left_length - 1 root.left = build(start1, end2 - right_length - 1, left_length) root.right = build(start1 + 1 + left_length, end2 - 1, right_length) return root
def build(start1, start2, length): if not length: return None root_val = preorder[start1] root = TreeNode(root_val) if length == 1: return root root_index = inorder.index(root_val) left_length = root_index - start2 right_length = length - left_length - 1 root.left = build(start1 + 1, start2, left_length) root.right = build(start1 + 1 + left_length, start2 + 1 + left_length, right_length) return root
def sortedListToBST(self, head): """ 升序链表,转二叉搜索树 :type head: ListNode :rtype: TreeNode """ if not head: return if not head.next: return TreeNode(head.val) slow, fast = head, head.next.next while fast and fast.next: fast = fast.next.next slow = slow.next tmp = slow.next slow.next = None root = TreeNode(tmp.val) root.left = self.sortedListToBST(head) root.right = self.sortedListToBST(tmp.next) return root