LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal

Description

https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

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

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

For example, given

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

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

Explanation

find inorder root position and update preorder list

Python 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:
        
        return self.helper(preorder, inorder);
                
    def helper(self, preorder, inorder):        

        if not inorder:
            return None
        
        inorder_position = inorder.index(preorder[0])        
                
        root = TreeNode(preorder[0])            
        root.left = self.helper(preorder[1 : 1 + inorder_position], inorder[0: inorder_position])
        root.right = self.helper(preorder[inorder_position + 1:], inorder[inorder_position + 1:])
                
        return root
  • Time complexity: O(N).
  • Space complexity: O(N).

One Thought to “LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal”

Leave a Reply

Your email address will not be published. Required fields are marked *