1. 程式人生 > >PAT A1102 Invert a Binary Tree 反轉二叉樹[二叉樹靜態寫法 後序遍歷反轉二叉樹]

PAT A1102 Invert a Binary Tree 反轉二叉樹[二叉樹靜態寫法 後序遍歷反轉二叉樹]

The following is from Max Howell @twitter: 

Google: 90% of our engineers use the software you wrote (Homebrew), but you can't invert a binary tree on a whiteboard so fuck off.

Now it's your turn to prove that YOU CAN invert a binary tree!

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤10) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node from 0 to N−1, and gives the indices of the left and right children of the node. If the child does not exist, a -

 will be put at the position. Any pair of children are separated by a space.

第一行給出一個正整數N(<=10),是二叉樹的總結點數。結點從0到N-1編號。後面有N行,每一行對應一個結點,給出這個結點的左孩子和右孩子的編號。如果沒有孩子,用-表示。

Output Specification:

For each test case, print in the first line the level-order, and then in the second line the in-order traversal sequences of the inverted tree. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.

第一行顯示反轉後的二叉樹的層次遍歷,第二行中序遍歷,相鄰數字之間用空格隔開,最後一個數字後面沒有空格

#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 110;

struct node{//二叉樹靜態寫法 
	int lchild,rchild;
}Node[maxn];

bool notRoot[maxn]={false};//記錄是否不是根節點, 初始均是根節點
int n,num=0;//n為結點個數,num為當前已經輸出的結點個數

//-----輸出結點id號 
void print(int id){
	printf("%d",id);
	num++;
	if(num<n) printf(" ");
	else printf("\n");
} 

//-------中序遍歷-----
void inOrder(int root){
	if(root == -1) return;
	inOrder(Node[root].lchild);
	print(root);
	inOrder(Node[root].rchild);
} 

//--------層次遍歷------
void BFS(int root){
	queue<int> q;
	q.push(root);
	while(!q.empty()){
		int now = q.front();
		q.pop();
		print(now);
		if(Node[now].lchild!=-1) q.push(Node[now].lchild);
		if(Node[now].rchild!=-1) q.push(Node[now].rchild);
	}
} 

//---------後序遍歷 用以反轉二叉樹-------
void postOrder(int root){
	if(root==-1) return;
	postOrder(Node[root].lchild);
	postOrder(Node[root].rchild);
	swap(Node[root].lchild,Node[root].rchild);
} 

//--------將輸入的字元轉換為-1或者結點編號--
int strToNum(char c){
	if(c=='-')return -1;
	else{
		notRoot[c-'0']=true;
		return c-'0';
	}
} 
//--------尋找根節點編號
int findRoot(){
	for(int i=0;i<n;i++){
		if(notRoot[i]==false){
			return i;
		}
	}
} 

int main(){
	char lchild,rchild;
	scanf("%d",&n);
	for(int i=0;i<n;i++){
		scanf("%*c%c %c",&lchild,&rchild);//%*c用來讀取換行符但不賦給任何變數 
		Node[i].lchild=strToNum(lchild);
		Node[i].rchild = strToNum(rchild);
	}
	int root = findRoot();
	postOrder(root);
	BFS(root);
	num=0;
	inOrder(root);
	return 0;
}