DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

Construct Binary Tree from Inorder and Postorder Traversal

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.

Example 1:

Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]

Example 2:

Input: inorder = [-1], postorder = [-1]
Output: [-1]

Constraints:

  • 1 <= inorder.length <= 3000
  • postorder.length == inorder.length
  • -3000 <= inorder[i], postorder[i] <= 3000
  • inorder and postorder consist of unique values.
  • Each value of postorder also appears in inorder.
  • inorder is guaranteed to be the inorder traversal of the tree.
  • postorder is guaranteed to be the postorder traversal of the tree.

SOLUTION:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def getRoot(self, p, q):
        return max((i for i in range(p, q)), key = lambda x: self.valIndex[self.inorder[x]])

    def buildTreeRec(self, p, q):
        if p < q:
            root = TreeNode()
            currRoot = self.getRoot(p, q)
            root.val = self.inorder[currRoot]
            if currRoot > p:
                root.left = TreeNode()
                root.left = self.buildTreeRec(p, currRoot)
            if currRoot < q - 1:
                root.right = TreeNode()
                root.right = self.buildTreeRec(currRoot + 1, q)
            return root

    def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        n = len(postorder)
        self.inorder = inorder
        self.valIndex = {}
        for i, item in enumerate(postorder):
            self.valIndex[item] = i
        return self.buildTreeRec(0, n)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)