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.
Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]
Input: inorder = [-1], postorder = [-1]
Output: [-1]
From: LeetCode
Link: 106. Construct Binary Tree from Inorder and Postorder Traversal
Given these insights, here’s the step-by-step approach:
The function build is a recursive helper function that constructs the tree. It accepts the current boundaries (start and end indices) of the inorder list it should consider. It also accepts a pointer to the current index in the postorder list, which is decremented with each recursive call.
The function buildTree is the main function that initiates the tree construction. It starts the process by setting the postorder index to the last element and calling the build function.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* build(int* inorder, int inStart, int inEnd,
int* postorder, int* postIndex) {
// Base condition
if (inStart > inEnd) return NULL;
// Allocate memory for the new node
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
// The current postIndex is the value of the root for this subtree
node->val = postorder[*postIndex];
node->left = NULL; // Initialize left child to NULL
node->right = NULL; // Initialize right child to NULL
(*postIndex)--;
// If there's no left or right children, return the node
if (inStart == inEnd) return node;
// Find the index of the current node in inorder to split left and right subtree
int inIdx;
for (inIdx = inStart; inIdx <= inEnd; inIdx++) {
if (inorder[inIdx] == node->val) break;
}
// Recursively build the right and then the left subtree
node->right = build(inorder, inIdx + 1, inEnd, postorder, postIndex);
node->left = build(inorder, inStart, inIdx - 1, postorder, postIndex);
return node;
}
struct TreeNode* buildTree(int* inorder, int inorderSize, int* postorder, int postorderSize) {
// Start from the end of postorder (which represents the root of the tree)
int postIndex = postorderSize - 1;
return build(inorder, 0, inorderSize - 1, postorder, &postIndex);
}