給定一棵二叉樹的後序遍歷和中序遍歷,請你輸出其層序遍歷的序列。這裡假設鍵值都是互不相等的正整數。
輸入格式:
輸入第一行給出乙個正整數
nn n(
≤30\le 30
≤30),是二叉樹中結點的個數。第二行給出其後序遍歷序列。第三行給出其中序遍歷序列。數字間以空格分隔。
輸出格式:
在一行中輸出該樹的層序遍歷的序列。數字間以1個空格分隔,行首尾不得有多餘空格。
輸入樣例:
7 2 3 1 5 7 6 4
1 2 3 4 5 6 7
輸出樣例:
4 1 6 3 5 7 2
已知後序與中序輸出前序(先序):
後序:3, 4, 2, 6, 5, 1(左右根)
中序:3, 2, 4, 1, 6, 5(左根右)
分析:因為後序的最後乙個總是根結點,令i在中序中找到該根結點,則i把中序分為兩部分,左邊是左子樹,右邊是右子樹。因為是輸出先序(根左右),所以先列印出當前根結點,然後列印左子樹,再列印右子樹。左子樹在後序中的根結點為root – (end – i + 1),即為當前根結點-右子樹的個數。左子樹在中序中的起始點start為start,末尾end點為i – 1.右子樹的根結點為當前根結點的前乙個結點root – 1,右子樹的起始點start為i+1,末尾end點為end。
輸出的前序應該為:1, 2, 3, 4, 5, 6(根左右)
#include
using
namespace
std ;
struct node
la[32];
int main()
int cnt2 = 0 ;
for(int i = re[ro.va]-1 ; i >= 0 ; i --)
if(ro.pos-cnt-1 >= 1 && cnt2 != 0)
s.push(la[ro.pos-cnt-1]); // 壓入左樹root
if(ro.pos-1 >= 1 && cnt != 0)
s.push(la[ro.pos-1]); // 壓入右樹root
ans ++ ;
printf("%d ",ro.va);
}node last = s.front();
printf("%d\n",last.va);
//printf("\n");
return
0 ;}
PAT甲級1004樹的遍歷
個人覺得這題沒有1003南欸,就乙個樹的遍歷,把根找出來dfs就完事了,非常莫得技術含量,居然有30分,感覺有點點德不配位,題不配分哈哈哈哈哈哈 include include include include include include include include define inf 40...
PAT 1086 樹的遍歷
給出中序和前序遍歷,求後序遍歷,只不過是間接的給出了遍歷序列 sample input 6 push 1 push 2 push 3 poppop push 4 poppop push 5 push 6 poppopsample output 4 2 6 5 1先是對輸入的處理,可以直接用strin...
PAT甲級 1020 樹的遍歷
用了乙個hash表方便後續的查詢工作。pos的作用是記錄中序遍歷中 的該值所在的陣列下標編號 int q n 模擬乙個佇列,用於輸出層序遍歷 intbuild int il,int ir,int pl,int pr void bfs int root 輸出個層序遍歷 int main int roo...