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:

Construct Binary Tree from Preorder and Inorder Traversal_第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

你可能感兴趣的:(leetcode算法学习,算法)