1. 程式人生 > >1020 Tree Traversals [二叉樹遍歷]

1020 Tree Traversals [二叉樹遍歷]

order new class 簡單介紹 pan 指針 view nor 起點

題目大意就是根據樹的後序遍歷和中序遍歷推出層序遍歷。

很久沒做過這種題了,正好借此復習一下數據結構。

首先是遍歷的幾個簡單介紹。

前序遍歷(preorder):根結點->左子樹->右子樹。

中序遍歷(inorder):左子樹->根結點->右子樹。

後序遍歷(postorder):左子樹->右子樹->根結點。

層序遍歷(level order):從根開始,依次向下,每一層從左向右遍歷。

技術分享圖片

前序遍歷:1 2 4 5 7 8 3 6

中序遍歷:4 2 7 5 8 1 3 6

後序遍歷:4 7 8 5 2 6 3 1

層次遍歷:1 2 3 4 5 6 7 8

接著來講講後序+中序->層序or前序

我們可以根據後序遍歷的最後一個點找到根節點,然後在中序遍歷中找到這個根節點,在根節點左邊的就是左子樹,右邊為右子樹。進而可以在後序遍歷中劃出左子樹和右子樹。同理得到的左子樹和右子樹也按該方法處理,最後即可得到這棵樹。

最後是代碼實現。

二叉樹用結構體指針處理。

上述思路用遞歸函數實現。每次遞歸更新子樹的中後序遍歷序列的起點和終點,返回當前樹的根節點。當後序序列的長度小於零時遞歸結束。

層序遍歷的輸出用BFS輸出即可。

技術分享圖片
#include <iostream>
#include 
<string.h> #include <cstdio> #include <string> #include <queue> using namespace std; #define maxn 35 struct node { int data; node *l; node *r; }tr[maxn]; int n; int a[maxn],b[maxn]; node* fun(int s1,int t1,int s2,int t2) { if(s1>t1)
return NULL; int pos; node *root=new node; root->data=a[t1]; for(int i=s2;i<=t2;i++) { if(b[i]==a[t1]) { pos=i; break; } } int ln=pos-s2; root->l=fun(s1,s1+ln-1,s2,pos-1); root->r=fun(ln+s1,t1-1,pos+1,t2); return root; } void BFS(node *root) { int cnt=0; node *t; queue<node*> q; q.push(root); while(!q.empty()) { t=q.front(); q.pop(); printf("%d",t->data); cnt++; if(cnt<n) printf(" "); if(t->l!=NULL) q.push(t->l); if(t->r!=NULL) q.push(t->r); } printf("\n"); } int main() { scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d",&a[i]); for(int i=0;i<n;i++) scanf("%d",&b[i]); node *root=fun(0,n-1,0,n-1); BFS(root); return 0; }
View Code

1020 Tree Traversals [二叉樹遍歷]