1. 程式人生 > 其它 >7-9 玩轉二叉樹 (25分)

7-9 玩轉二叉樹 (25分)

技術標籤:HBU2021寒假訓練營c語言

7-9 玩轉二叉樹 (25分)

給定一棵二叉樹的中序遍歷和前序遍歷,請你先將樹做個鏡面反轉,再輸出反轉後的層序遍歷的序列。所謂鏡面反轉,是指將所有非葉結點的左右孩子對換。這裡假設鍵值都是互不相等的正整數。

輸入格式:

輸入第一行給出一個正整數N(≤30),是二叉樹中結點的個數。第二行給出其中序遍歷序列。第三行給出其前序遍歷序列。數字間以空格分隔。

輸出格式:

在一行中輸出該樹反轉後的層序遍歷的序列。數字間以1個空格分隔,行首尾不得有多餘空格。

輸入樣例:

7
1 2 3 4 5 6 7
4 1 3 2 6 5 7

輸出樣例:

4 6 1 7 5 3
2

思路:

這題就是把二叉樹的幾個函式結合到一塊,還原二叉樹、層次遍歷、交換孩子結合起來就行了,這種題以前也都做過:樹的遍歷還原二叉樹

AC程式碼:

#include<bits/stdc++.h>
using namespace std;
typedef struct btnode{
	int data;
	struct btnode *left,*right;
}BTnode,*BTree;
int preod[10010],inod[10010];	//一個是先序陣列,一個是中序陣列 
BTree Retree(int root,int begin,int end){	//Retree目的是通過先序和中序遍歷還原二叉樹 
//root是先序中的根結點,begin是中序的開頭,end是中序的結尾 if(begin > end) return NULL; int tp; for(tp = begin;tp < end;tp++){ //找到先序中的根結點,位於中序中的什麼位置 if(preod[root] == inod[tp]) break; } BTnode *node = new BTnode; node->data = preod[root]; node->left = Retree(root+1,begin,tp-1); node->right =
Retree(root+1+tp-begin,tp+1,end); return node; } BTree change(BTree bt){ if(!bt->left && !bt->right){ return bt; }else{ BTree a1,a2; if(bt->left){ a1 = change(bt->left); }else{ a1 = NULL; } if(bt->right){ a2 = change(bt->right); }else{ a2 = NULL; } bt->left = a2; bt->right = a1; return bt; } } void bfs(BTree bt) { //通過佇列實現二叉樹的層序遍歷 BTnode *queue[100]; int front = -1,rear = 0; int flag = 0; if(bt == NULL) return; queue[rear] = bt; while(front != rear){ //當front和rear相等時佇列為空 front++; if(flag++) cout << " "; cout << queue[front]->data; if(queue[front]->left != NULL){ rear++; queue[rear] = queue[front]->left; } if(queue[front]->right != NULL){ rear++; queue[rear] = queue[front]->right; } } } int main(){ int n; cin >> n; for(int i = 0;i < n;i++) cin >> inod[i]; for(int i = 0;i < n;i++) cin >> preod[i]; BTree bt; bt = Retree(0,0,n-1); bfs(change(bt)); }