【原創】二叉樹的建立與遍歷(前序遍歷、中序遍歷、後序遍歷)
阿新 • • 發佈:2019-02-12
二叉樹的建立與遍歷(binary-tree)
題目描述
給出一棵二叉樹,分別輸出先序、中序、後序遍歷結果。
輸入
第一行:結點數n(1<=n<=100)。
以下n行,每行3個整數,分別表示父結點、左孩子、右孩子。若沒有孩子,對應的整數為0.
輸出
第1行:樹根
第2行:先序遍歷結果,數字間用1個空格分開。
第3行:中序遍歷結果,數字間用1個空格分開。
第4行:後序遍歷結果,數字間用1個空格分開。
樣例輸入
8
1 2 4
2 0 0
4 8 0
3 1 5
5 6 0
6 0 7
8 0 0
7 0 0
樣例輸出
3
3 1 2 4 8 5 6 7
2 1 8 4 3 6 7 5
2 8 4 1 7 6 5 3
分析:
我們今天學了二叉樹,我深有感觸。
neixinos();
二叉樹是一種很有用(但不好用)的資料結構,在各種題目中都有它的身影。(That's why I hate it)。
二叉樹最基本的應用就是遍歷,比較常規的遍歷方法有:
1.先序:又叫前序,先根,英文為preorder,也叫DLR。具體步驟有:
①訪問根結點 ②訪問左結點 ③訪問右結點
2.中序:又叫中根,英文為inorder,也叫LDR。具體步驟有:
①訪問左結點 ②訪問根結點 ③訪問右結點
3.後序:又叫後根,英文為postorder,也叫LRD。具體步驟有:
①訪問左結點 ②訪問右結點 ③訪問根結點
詳見程式碼:
#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<algorithm> #include<cmath> #include<cstdlib> using namespace std; struct Epic { int data; int left,right,up; }tree[123]; int root,n,sp; void input() { int a,b,c; scanf("%d",&n); for(int i=1;i<=n;i++) tree[i].data=i; for(int i=1;i<=n;i++) { scanf("%d %d %d",&a,&b,&c); tree[a].left=b; tree[a].right=c; tree[b].up=a; tree[c].up=a; } for(int i=1;i<=n;i++) if(!tree[i].up) root=i; printf("%d\n",root); } void DLR(int i) { if(i!=0) { if(sp) printf(" "); else sp++; printf("%d",tree[i].data); DLR(tree[i].left); DLR(tree[i].right); } } void LDR(int i) { if(i!=0) { LDR(tree[i].left); if(sp) printf(" "); else sp++; printf("%d",tree[i].data); LDR(tree[i].right); } } void LRD(int i) { if(i!=0) { LRD(tree[i].left); LRD(tree[i].right); if(sp) printf(" "); else sp++; printf("%d",tree[i].data); } } int main() { input(); sp=0; DLR(root); sp=0; printf("\n"); LDR(root); sp=0; printf("\n"); LRD(root); return 0; }
內心os()
{
好難啊!!!
}