LeetCode: 106. Construct binary tree from inorder and postorder traversal sequences

Time limit: 5000MS
Memory limit: 589824KB
Title description:
Given two integer arrays inorder and postorder, where inorder is the inorder traversal of a binary tree, and postorder is the postorder traversal of the same tree, please return the preorder traversal of this binary tree.
Input description
The in-order traversal of the input element binary tree and the post-order traversal of the same tree
Output description
The output is the pre-order traversal of the binary tree
Sample input
9 3 15 20 7
9 15 7 20 3
Sample output
3 9 20 15 7
 

"""
算法思路:根据中序遍历和后序遍历重建二叉树,然后先序遍历即可。

具体步骤如下:

1. 后序遍历的最后一个节点即为根节点,找到根节点在中序遍历中的位置,将中序遍历分为左子树和右子树。

2. 根据左子树和右子树的长度,将后序遍历也分为左子树和右子树。

3. 递归重建左子树和右子树。

4. 先序遍历的顺序为根节点、左子树、右子树。

时间复杂度:$O(n)$,其中$n$为二叉树节点个数。

空间复杂度:$O(n)$,需要存储中序遍历和后序遍历的数组,以及递归时的栈空间。

参考代码:
如下
"""
from typing import List

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
        if not inorder or not postorder:
            return None
        root_val = postorder[-1]
        root = TreeNode(root_val)
        idx = inorder.index(root_val)
        root.left = self.buildTree(inorder[:idx], postorder[:idx])
        root.right = self.buildTree(inorder[idx+1:], postorder[idx:-1])
        return root

    def preorderTraversal(self, root: TreeNode) -> List[int]:
        if not root:
            return []
        res = []
        stack = [root]
        while stack:
            node = stack.pop()
            res.append(node.val)
            if node.right:
                stack.append(node.right)
            if node.left:
                stack.append(node.left)
        return res

if __name__ == '__main__':
    inorder = list(map(int, input().split()))
    postorder = list(map(int, input().split()))
    s = Solution()
    root = s.buildTree(inorder, postorder)
    res = s.preorderTraversal(root)
    print(' '.join(map(str, res)))

Guess you like

Origin blog.csdn.net/dsafefvf/article/details/130971492