一、题目链接
给定两个整数数组 inorder
和 postorder
,其中 inorder
是二叉树的中序遍历, postorder
是同一棵树的后序遍历,请你构造并返回这颗二叉树。
示例 1:
输入:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
输出:[3,9,20,null,null,15,7]
示例 2:
输入:inorder = [-1], postorder = [-1]
输出:[-1]
二、题解
class Solution {
public:
TreeNode* buildTree(vector<int> &inorder, vector<int> &postorder) {
return buildSubTree(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1);
}
TreeNode* buildSubTree(vector<int> &inorder, vector<int> &postorder, int in_begin, int in_end, int post_begin, int post_end) {
int cur_val = postorder.at(post_end);
int cur_val_at_inorder = in_begin;
while (inorder.at(cur_val_at_inorder) != cur_val) {
cur_val_at_inorder++;
}
int left_count = cur_val_at_inorder - in_begin;
int right_count = in_end - cur_val_at_inorder;
TreeNode *new_node = new TreeNode(cur_val);
if (left_count) {
new_node->left = buildSubTree(inorder, postorder, in_begin, cur_val_at_inorder - 1, post_begin, post_begin + left_count - 1);
}
if (right_count) {
new_node->right = buildSubTree(inorder, postorder, cur_val_at_inorder + 1, in_end, post_begin + left_count, post_end - 1);
}
return new_node;
}
};