A1102

二叉樹反轉reverse:每個根結點的左右子樹交換位置.
因爲題目直接給的是結點編號的關係,因此本題用二叉樹的靜態寫法會非常方便.
swap()交換左右孩子位置.

#include<cstdio>
#include<cstdlib>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<string>
#include<algorithm>
using namespace std;
bool isroot[11]={false};
int n,now=0;
struct node{
	int data;
	int lchild;
	int rchild;
}nodes[11];
int change(char c){
	if(c=='-')return -1;
	else{
		int t=c-'0';
		isroot[t]=true;
		return c-'0';
	} 
}
int findroot(){
	for(int i=0;i<n;i++){
		if(isroot[i]==false){
			return i;
		}
	}
}
//使用後續遍歷實現二叉樹的反轉
void reverse(int root){
	if(root==-1)return;
	reverse(nodes[root].lchild);
	reverse(nodes[root].rchild);
	swap(nodes[root].lchild,nodes[root].rchild);
}
void levelorder(int root){
	queue<int> q;
	q.push(root);
	while(!q.empty()){
		int now=q.front();
		q.pop();
		if(nodes[now].lchild!=-1){
			q.push(nodes[now].lchild);
		}
		if(nodes[now].rchild!=-1){
			q.push(nodes[now].rchild);
		}
		if(q.empty()){
			printf("%d",now);
		}else{
			printf("%d ",now);
		}
	}
}
void inorder(int root){
	if(root==-1)return;
	inorder(nodes[root].lchild);
	now++;
	if(now==n){
		printf("%d",root);
	}else{
		printf("%d ",root);
	}
	inorder(nodes[root].rchild);
}
int main(){
	#ifdef ONLINE_JUDGE
	#else
		freopen("1.txt","r",stdin);
	#endif
	char l,r;
	scanf("%d",&n);
	for(int i=0;i<n;i++){
		getchar();
		scanf("%c %c",&l,&r);
		nodes[i].lchild=change(l);
		nodes[i].rchild=change(r);
	}
	int root=findroot();
	reverse(root);
	levelorder(root);
	printf("\n");
	inorder(root);
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章