Skip to main content

105. Construct Binary Tree from Preorder and Inorder Traversal

Hint

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
// rootIndex is used to represent the current root node index in preorder

// indexMap is used to store the index of each node in inorder

public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder)
{
// Store each value and its index in inorder into indexMap

// Call the recursive function to build the binary tree and return the root node
}

// build function is used to recursively build the subtree
TreeNode* build(vector<int>& preorder, int left, int right)
{
// If left > right, it indicates that the current interval is invalid, return a null node

// Get the value of the root node according to preorder[rootIndex] and move rootIndex forward

// Create the root node

// Find the index position of the root node in inorder to divide the left and right subtrees

// Recursively build the left subtree, the interval of the left subtree is [left, inorderIndex - 1]

// Recursively build the right subtree, the interval of the right subtree is [inorderIndex + 1, right]

// Return the root node to complete the construction of the current subtree
}
};
  • Recursion
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
int rootIndex = 0;
unordered_map<int, int> indexMap;
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder)
{
int n = preorder.size();

for(int i = 0; i < n; ++i)
{
indexMap[inorder[i]] = i;
}
return build(preorder, 0, n - 1);
}

TreeNode* build(vector<int>& preorder, int left, int right)
{
if(left > right) return nullptr;

int rootValue = preorder[rootIndex++];

TreeNode* root = new TreeNode(rootValue);

root->left = build(preorder, left, indexMap[rootValue] - 1);

root->right = build(preorder, indexMap[rootValue] + 1, right);
return root;
}
};
  • T: O(N)O(N)
  • S: O(N)O(N)