Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal
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]
inorder
and postorder
?
postorder
array is the root of the tree.inorder
array into left and right subtrees.inorder
array for quick access.inorder
and postorder
arrays.postorder
array segment, find its position in the inorder
array to split the tree, and recursively build the left and right subtrees.#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
// 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 {
public:
unordered_map<int, int> inorder_map;
TreeNode* buildTreeHelper(vector<int>& inorder, vector<int>& postorder, int in_left, int in_right, int& post_index) {
// Base case
if (in_left > in_right) {
return nullptr;
}
// Get the current root value
int root_val = postorder[post_index--];
TreeNode* root = new TreeNode(root_val);
// Root splits inorder list into left and right subtrees
int index = inorder_map[root_val];
// Build right subtree first as postorder is traversed from back
root->right = buildTreeHelper(inorder, postorder, index + 1, in_right, post_index);
root->left = buildTreeHelper(inorder, postorder, in_left, index - 1, post_index);
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
for (int i = 0; i < inorder.size(); ++i) {
inorder_map[inorder[i]] = i;
}
int post_index = postorder.size() - 1;
return buildTreeHelper(inorder, postorder, 0, inorder.size() - 1, post_index);
}
};
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?