Construct Binary Tree from Preorder and Inorder Traversal

Problem Id: 105 Difficulty: Medium Tag: Array Tag: Tree Tag: Depth-first Search


Intuition

if we say the first node is a0, then inorder could be splited into 3 parts Al + [a0] + Ar. Al is the inorder of the left subtree of the node a0 while Ar is the right subtree.

Here comes this recursive solution.

Solution


# 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, preorder: List[int], inorder: List[int]) -> TreeNode:
        if len(preorder) == 0:
            return None

        mid = inorder.index(preorder[0])
        node = TreeNode(preorder[0])
        node.left = self.buildTree(preorder[1:mid + 1], inorder[:mid])
        node.right = self.buildTree(preorder[mid + 1:], inorder[mid + 1:])
        return node