
Given two integer arrays preorder and inorder, you are required to reconstruct a binary tree. These arrays represent the preorder and inorder traversals of a binary tree, respectively. The preorder array provides the root-first traversal sequence of the tree, while the inorder array offers a left-root-right traversal sequence. Utilizing these two sequences, you are to build and return the binary tree structure that conforms to these traversal orders.
Input:
Output:
Input:
Output:
1 <= preorder.length <= 3000inorder.length == preorder.length-3000 <= preorder[i], inorder[i] <= 3000preorder and inorder consist of unique values.inorder also appears in preorder.preorder is guaranteed to be the preorder traversal of the tree.inorder is guaranteed to be the inorder traversal of the tree.When tackling the problem of reconstructing a binary tree from its preorder and inorder traversal data, it’s crucial to understand the basic properties of these traversals:
Using the above properties, we can infer the following steps to reconstruct the tree:
The recursion leverages the first element extraction in the preorder array to identify root nodes and uses the root’s index in the inorder array to delineate bounds of left and right subtrees. Since both arrays contain unique values and each value from one also appears in the other, this method reliably constructs the correct binary tree structure.
Explore the C++ solution that efficiently constructs a binary tree from preorder and inorder traversal arrays. The key components of this solution involve utilizing recursion and hash mapping to maintain track of indices, which significantly optimizes the search process within the inorder array.
Define the class Solution with private members:
currentPreorderIndex to keep track of the index for the currently being processed node in the preorder array.indexMap to store the index of each value in the inorder array for quick access.Implement the buildSubTree method:
start and end) as parameters.nullptr indicating no subtree is formed.currentPreorderIndex and increment it.TreeNode with the root value.start to indexMap[rootVal] - 1.indexMap[rootVal] + 1 to end.TreeNode.Implement the buildTree method:
currentPreorderIndex to 0.indexMap where each key-value pair consists of a value from the inorder array and its corresponding index.buildSubTree with bounds from 0 to preorder.size() - 1.This approach, leveraging a hash map and recursion, allows for swift and efficient reconstruction of the binary tree without searching the entire inorder array repeatedly for the root element, which makes it time-efficient. This technique greatly reduces the time complexity typically encountered in tree construction problems.
0 Comments
Be the first to comment and share your perspective with the community.