#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
struct Node{
int val;
Node* left;
Node* right;
Node(int x):val(x),left(nullptr),right(nullptr) {}
};
Node* buidTree(std::vector<int> pre_order, std::vector<int> in_order) {
Node* root = nullptr;
if (pre_order.empty()) {
return root;
}
std::stack<node*> st;
root = new Node(pre_order[0]);
st.push(root);
int in_idx = 0;
for (int pre_idx = 1; pre_idx < pre_order.size(); pre_idx++) {
int val = pre_order[pre_idx];
node* cur = st.top();
if ( cur->val != in_order[in_idx]) {
cur->left = new Node(val);
st.push(cur->left);
} else {
while(!st.empty() && st.top()->val == in_order[in_idx]) {
cur = st.top();
st.pop();
in_idx ++;
}
cur->right = new Node(in_order[in_idx]);
st.push(cur->right);
}
}
return root;
}
通过中序和后续,重构二叉树:
Node* buidTree(std::vector<int> post_order, std::vector<int> in_order) {
if (post_order.empty()) {
return nullptr;
}
int size = post_order.size();
Node* root = new Node(post_order[size - 1]);
std::stack<Node*> st;
st.push(root);
int in_idx = size-1;
for (auto idx=size-2; idx >= 0; idx--) {
int val = post_order[idx];
Node* cur = st.top();
if (cur->val != in_order(in_idx)) {
cur->right = new Node(val);
st.push(cur->right);
} else {
if (!st.empty() && st.top()->val == in_order(in_idx)) {
cur = st.top()
st.pop();
in_idx --;
}
cur->right = new Node(val);
st.push(cur->right);
}
}
return root;
}