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.
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
Input: preorder = [-1], inorder = [-1]
Output: [-1]
From: LeetCode
Link: 105. Construct Binary Tree from Preorder and Inorder Traversal
The idea behind the solution is based on the following key observations regarding the properties of the preorder and inorder traversals of a binary tree:
Using these properties, the algorithm constructs the binary tree in the following manner:
Base Case: If the provided subsections of the preorder or inorder lists are empty (i.e., start index is greater than the end index), return NULL. This means there’s no tree to be constructed for that particular subsection.
Recursive Steps:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int indexOf(int* arr, int start, int end, int value) {
for (int i = start; i <= end; i++) {
if (arr[i] == value) {
return i;
}
}
return -1;
}
struct TreeNode* helper(int* preorder, int preorderStart, int preorderEnd,
int* inorder, int inorderStart, int inorderEnd) {
if (preorderStart > preorderEnd || inorderStart > inorderEnd) {
return NULL;
}
// Create the root node with the first value of the preorder list
struct TreeNode* root = (struct TreeNode*) malloc(sizeof(struct TreeNode));
root->val = preorder[preorderStart];
// Get the position of root in inorder
int rootIndex = indexOf(inorder, inorderStart, inorderEnd, root->val);
// Calculate the length of the left and right subtrees
int leftTreeLength = rootIndex - inorderStart;
int rightTreeLength = inorderEnd - rootIndex;
// Construct left and right subtrees
root->left = helper(preorder, preorderStart + 1, preorderStart + leftTreeLength,
inorder, inorderStart, rootIndex - 1);
root->right = helper(preorder, preorderStart + leftTreeLength + 1, preorderEnd,
inorder, rootIndex + 1, inorderEnd);
return root;
}
struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize) {
return helper(preorder, 0, preorderSize - 1, inorder, 0, inorderSize - 1);
}