一個無重復的非負整數序列,必定對應唯一的一棵形狀為完全二叉樹的二叉搜索樹。本題就要求你輸出這棵樹的層序遍歷序列。
輸入格式:
首先第一行給出一個正整數 N(≤),隨后第二行給出 N 個不重復的非負整數。數字間以空格分隔,所有數字不超過 2000。
輸出格式:
在一行中輸出這棵樹的層序遍歷序列。數字間以 1 個空格分隔,行首尾不得有多余空格。
輸入樣例:
10
1 2 3 4 5 6 7 8 9 0
輸出樣例:
6 3 8 1 5 7 9 0 2 4
題目==已知搜索樹中序遍歷求層序遍歷

#include<bits/stdc++.h> using namespace std; int mp[1005],a[1005],cnt,n; void dfs(int x) { if(x>n)return ; dfs(x*2); a[x]=++cnt;//該行的位置變換 也可以由先序后序推出層序 //x表示層序遍歷時第x個出現 //cnt 表示中序遍歷時的下標 dfs(2*x+1); } int main() { int i;cin>>n; for(i=1;i<=n;i++)cin>>mp[i]; sort(mp+1,mp+1+n); dfs(1); for(i=1;i<=n;i++){ if(i!=1)cout<<" "; cout<<mp[a[i]]; } }
上面dfs記錄的是中序遍歷時的該數 在層序遍歷時出現的下標;cnt不斷累加表示中序遍歷,x表示層序遍歷時的下標
下面層序推中序的dfs就直接根據層序的下標,搜出中序遍歷時的順序 然后直接按序輸出

#include<bits/stdc++.h> using namespace std; int n,mp[1005]; void dfs(int x) { if(x>n)return; dfs(x*2); printf("%d ",mp[x]); dfs(x*2+1); return; } int main() { int i;cin>>n; for(i=1;i<=n;i++)cin>>mp[i]; dfs(1); return 0; }