LeetCode | 0106. Construct Binary Tree from Inorder and Postorder Traversal from order traversal sequence after sequence and structure of a binary tree [Python]

LeetCode 0106. Construct Binary Tree from Inorder and Postorder Traversal sequence therefrom and configured postorder binary sequence [Python Medium] [] [] [recursive binary tree]

Problem

LeetCode

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

For example, given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

problem

Power button

Traversing the binary tree is configured in accordance with the sequence preorder a tree.

Note:
You can assume that the tree does not duplicate elements.

For example, given

中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]

Returns the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

Thinking

Recursion

中序遍历:左根右
后序遍历:左右根

于是,每次取后序遍历末尾的值,表示根,再到中序遍历中确定索引。
再根据索引,分割成左子树和右子树。如此递归。

注意:
保证递归的 inorder 和 postorder 个数一致。

Time complexity: O (n-), n-number of nodes.
Space complexity: O (n-), n-number of nodes.

Python3 Code
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
        if not postorder:
            return None
        root = TreeNode(postorder[-1])

        # 根在中序遍历中的索引
        i = inorder.index(root.val)
        # left: inorder[0] ~ inorder[i-1], postorder[0] ~ postorder[i-1]
        root.left = self.buildTree(inorder[:i], postorder[:i])
        # right: inorder[i+1] ~ inorder[-1], postorder[i] ~ postorder[-2]
        root.right = self.buildTree(inorder[i+1:], postorder[i:-1])

        return root

Code address

GitHub link

Guess you like

Origin www.cnblogs.com/wonz/p/12520211.html