Solving Leetcode Interviews in Seconds with AI: Construct Binary Tree from Inorder and Postorder Traversal
Introduction
In this blog post, we will explore how to solve the LeetCode problem "106" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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.
Explanation
Here's the approach and Python code to solve the binary tree construction problem:
Core Idea: The postorder traversal gives us the root of the tree (the last element). The inorder traversal allows us to divide the tree into left and right subtrees based on the root's position.
Recursive Construction: Recursively build the left and right subtrees. The inorder array defines the bounds of the left and right subtrees, and these bounds are used to extract the corresponding sections from the postorder array.
Optimization: Use a hash map (dictionary in Python) to store the index of each element in the inorder array. This avoids repeated linear searches within the inorder array to find the root's position, significantly improving performance.
Complexity:
- Runtime: O(N), where N is the number of nodes in the tree.
- Storage: O(N) due to the hash map and recursion stack (in the worst case, a skewed tree).
Code
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def buildTree(inorder, postorder):
inorder_index_map = {val: idx for idx, val in enumerate(inorder)}
postorder_index = len(postorder) - 1
def build_subtree(inorder_start, inorder_end):
nonlocal postorder_index
if inorder_start > inorder_end:
return None
root_val = postorder[postorder_index]
root = TreeNode(root_val)
postorder_index -= 1
inorder_root_index = inorder_index_map[root_val]
# Construct right subtree first because of postorder traversal
root.right = build_subtree(inorder_root_index + 1, inorder_end)
root.left = build_subtree(inorder_start, inorder_root_index - 1)
return root
return build_subtree(0, len(inorder) - 1)