給定一個(gè)二叉樹(shù)的中序和層序輸出,重建二叉樹(shù)并按先序和后序輸出。
#include#includeusing namespace std;
struct TreeNode {
int data;
TreeNode* leftchild;
TreeNode* rightchild;
TreeNode(int n) {
data = n;
}
};
vectorceng;
vectormid;
vectorpre;
vectorpost;
TreeNode* BuildTree(int cl, int cr, int ml, int mr);
void preOrder(TreeNode* r);
void PostOrder(TreeNode* r);
int main() {
int num;
cin >>num;
int temp;
for (int i = 0; i< num; i++) {
cin >>temp;
ceng.push_back(temp);
}
for (int i = 0; i< num; i++) {
cin >>temp;
mid.push_back(temp);
}
TreeNode* root = BuildTree(0, num - 1, 0, num - 1);
preOrder(root);
PostOrder(root);
for (int i = 0; i< num - 1; i++) {
cout<< pre[i]<<" ";
}
cout<< pre[num - 1]<< endl;
for (int i = 0; i< num - 1; i++) {
cout<< post[i]<< " ";
}
cout<< post[num - 1]<< endl;
}
TreeNode* BuildTree(int cl, int cr, int ml, int mr)
{
if(ml>mr)
return nullptr;
int i, j;
int cnt = 0;
for (i = cl; i<= cr; i++) {
for ( j = ml; j<= mr; j++) {
if (ceng[i] == mid[j]) {
cnt = 1;
break;
}
}
if (cnt == 1)
break;
}
TreeNode* r = new TreeNode(ceng[i]);
r->leftchild = BuildTree(cl + 1, cr, ml, j - 1);
r->rightchild = BuildTree(cl + 1, cr, j + 1, mr);
return r;
}
void preOrder(TreeNode* r)
{
if (r == NULL)
return;
pre.push_back(r->data);
preOrder(r->leftchild);
preOrder(r->rightchild);
}
void PostOrder(TreeNode* r)
{
if (r == NULL)
return;
PostOrder(r->leftchild);
PostOrder(r->rightchild);
post.push_back(r->data);
}
你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機(jī)房具備T級(jí)流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級(jí)服務(wù)器適合批量采購(gòu),新人活動(dòng)首月15元起,快前往官網(wǎng)查看詳情吧