Problem Statement in English

You’re 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. Construct and return the binary tree.


Approach

This is very similar to problem 105. Construct Binary Tree From Preorder And Inorder Traversal. The only difference is that we are given the postorder traversal instead of the preorder traversal.

Since it’s a postorder traversal, the rightmost element is the root of the tree. The elements to the left of the root in the inorder traversal form the left subtree, and the elements to the right of the root in the inorder traversal form the right subtree.

And we’re done!


Solution in Python


class Solution:
    def buildTree(self, inorder: list[int], postorder: list[int]) -> TreeNode | None:
        def solve(ino, post):
            if not post or not ino:
                return None

            index = ino.index(post[-1])
            root = TreeNode(post[-1])

            root.left = solve(ino[:index], post[:index])
            root.right = solve(ino[index + 1:], post[index:-1])

            return root

        return solve(inorder, postorder)

Complexity

  • Time: $O(n^2)$
    Since we are using the index function to find the index of the root in the inorder list, which takes O(n) time, and we are doing this for each node in the tree, leading to a total time complexity of O(n^2).

  • Space: $O(n^2)$
    Since we are creating new lists for the left and right subtrees in each recursive call, the space complexity is also $O(n^2)$.


And we are done.