- postorder的最后一位是root;
- 从头开始遍历inorder输出, 直到找到root, 计数个数为左子树个数j;
- 确定第一层左子树右子树的索引位置:
- postorder: 左子树0 - j-1, 右子树 j+1 - length-2
- inorder: 左子树0- j-1, 右子树 j + 1 - length -1
- 分别递归下一层
#include <iostream>
#include <vector>
struct Node {
int value;
struct Node* left;
struct Node* right;
Node(int val):
value(val) {}
};
struct Node* buildBinaryTree(const std::vector<int>& postorder, int post_start, int post_end, const std::vector<int>& inorder, int in_start, int in_end) {
struct Node* root = new Node(postorder[post_end]);
if (post_end - post_start == 0) {
return root;
}
int j = -1;
while (inorder[in_start + ++j] != root->value && in_start + j <= in_end) ;
if (j > in_end) {
throw std::range_error("can't find root:" + std::to_string(root->value));
}
root->left = buildBinaryTree(postorder, post_start, post_start + j - 1, inorder, in_start, in_start + j - 1);
root->right = buildBinaryTree(postorder, post_start + j, post_end - 1, inorder, in_start + j + 1, in_end);
return root;
}
void inorder_print(struct Node* root) {
if (root == nullptr) return;
inorder_print(root->left);
std::cout << root->value << std::endl;
inorder_print(root->right);
}
int main() {
std::vector<int> post_order = {3, 5, 6, 7, 4};
std::vector<int> in_order = {3, 4, 5, 7, 6};
struct Node* root = buildBinaryTree(post_order, 0, post_order.size() - 1,
in_order, 0, in_order.size() - 1);
inorder_print(root);
}