思考:如何才能確定一棵樹?
結論: 通過中序遍歷和先序遍歷可以確定乙個樹
通過中序遍歷和後續遍歷可以確定乙個樹
通過先序遍歷和後序遍歷確定不了乙個樹。
演算法實現:
(一)先序和中序重建二叉樹,按層次遍歷輸出
#include #include #include #include #include #include #include using namespace std;
struct node
;node* tmpparent = nullptr;
node* createbt1(char* pre, char* in, int n)
int first_flag = 0;
void layerorder(node * root)
cout << tmp->data;
first_flag = 1;
if (tmp->lchild != null) ans.push(tmp->lchild);
if (tmp->rchild != null) ans.push(tmp->rchild);
}}void dispbtnode(node* b)
}}int main()
for (int i = 0; i> in[i];
}*/char str1[40] = ; char str2[40] = ;
printf("請輸入先序序列\n"); scanf("%s", str1);
printf("請輸入中序序列\n"); scanf("%s", str2);
int n = strlen(str1);
node * root;
root = createbt1((char*)str1, (char*)str2, n);
printf("按中序序列將新建的二叉樹輸出\n");
dispbtnode(root);
printf("按後序序列將新建的二叉樹輸出\n");
(二)根據後序序列和中序序列重建樹,按層次遍歷輸出關於怎樣由後序和中序重建二叉樹原理讀者可以自己查書,本博文僅供作者自己筆記之用
//**:
#include #include #include using namespace std;
struct node
;node* createbt2(char* post/*指向後序序列開頭的指標*/, char* in/*指向中序序列開頭的指標*/, int n)
/****************列印各節點***********************/
int first_flag = 0;
void layerorder(node * root)
cout << tmp->data;
first_flag = 1;
if (tmp->lchild != null) ans.push(tmp->lchild);
if (tmp->rchild != null) ans.push(tmp->rchild);
}}int main()
; char str2[40] = ;
printf("請輸入先序序列\n"); scanf("%s", str1);
printf("請輸入先序序列\n"); scanf("%s", str2);
node * root = createbt2(str1, str2, n);
layerorder(root);
return 0;
}
已知先序和中序求後序或中序和後序求先序
首先介紹樹的三種遍歷方式的遍歷順序 先序遍歷 根 左子樹 右子樹 特點 第乙個元素為根 中序遍歷 左子樹 根 右子樹 特點 根的兩邊分別為左子樹和右子樹 後序遍歷 左子樹 右子樹 根 特點 最後乙個元素為根 有如下圖的二叉樹 其先序 中序 後序遍歷分別為 dbacegf abcdefg acbfge...
後序 中序 》先序
已知後序與中序輸出前序 先序 後序 3,4,2,6,5,1 左右根 中序 3,2,4,1,6,5 左根右 分析 因為後序的最後乙個總是根結點,令i在中序中找到該根結點,則i把中序分為兩部分,左邊是左子樹,右邊是右子樹。因為是輸出先序 根左右 所以先列印出當前根結點,然後列印左子樹,再列印右子樹。左子...
根據後序和中序遍歷輸出先序遍歷
本題要求根據給定的一棵二叉樹的後序遍歷和中序遍歷結果,輸出該樹的先序遍歷結果。輸入格式 第一行給出正整數nn le 30 30 是樹中結點的個數。隨後兩行,每行給出nn個整數,分別對應後序遍歷和中序遍歷結果,數字間以空格分隔。題目保證輸入正確對應一棵二叉樹。輸出格式 在一行中輸出preorder 以...