Construct Binary Tree from Preorder and Inorder Traversal

Problem

Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.

Example 1:

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

Example 2:

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

Intuition

The task is to construct a binary tree given its preorder and inorder traversals. The preorder traversal provides information about the root of the tree and its left and right subtrees, while the inorder traversal helps determine the order in which the left and right subtrees are arranged.

Approach

Base Case:

Check if both preorder and inorder are empty. If so, return None since there are no more nodes to construct.
Root Node:

Create the root node using the first element of preorder (preorder[0]).
Find the index of the root value in inorder (mid). This index divides the inorder list into left and right subtrees.
Recursive Construction:

Recursively construct the left subtree using the sublist of preorder and inorder corresponding to the left subtree.
Recursively construct the right subtree using the sublist of preorder and inorder corresponding to the right subtree.
Return Result:

Return the root node of the constructed binary tree.

Complexity

  • Time complexity:

The time complexity is O(n^2) in the worst case, where n is the number of nodes in the binary tree. This is because finding the index of the root value in the inorder list takes O(n) time, and this operation is performed for each node in the tree. In the average case, the time complexity is O(nlogn) if a more efficient data structure (e.g., hashmap) is used to find the index.

  • Space complexity:

The space complexity is O(n) as each recursive call creates new nodes for the binary tree, and in the worst case, the maximum depth of the recursion is equal to the number of nodes in the tree.

Code

# 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 buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        if not preorder and not inorder:
            return None

        root = TreeNode(preorder[0])
        mid = inorder.index(preorder[0])
        root.left = self.buildTree(preorder[1:mid + 1], inorder[:mid])
        root.right = self.buildTree(preorder[mid + 1:], inorder[mid + 1:])
        return root
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值