Matter
很标准的一道题目,考察了前序遍历,后序遍历,层序遍历,可以作为一个模板使用。
Code
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
const int MAXN = 15;
int num = 0 , n;
bool notroot[MAXN] = {false};
struct node{
int lchild , rchild;
}Node[MAXN];
void print(int a){
printf("%d" , a);
num ++;
if(num < n) printf(" ");
else printf("\n");
}
int strNum(char c){
if(c == '-') return -1;
else{
notroot[c - '0'] = true;
return c - '0';
}
}
int find_root(){
for(int i = 0 ; i < n ; i ++){
if(notroot[i] == false){
return i;
}
}
}
void post_order(int root){
if(root == -1) return ;
post_order(Node[root].lchild);
post_order(Node[root].rchild);
swap(Node[root].lchild , Node[root].rchild);
}
void BFS(int root){
queue<int> q;
q.push(root);
while(q.empty() == false){
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 in_order(int root){
if(root == -1) return ;
in_order(Node[root].lchild);
print(root);
in_order(Node[root].rchild);
}
int main(){
//input
scanf("%d" , &n);
for(int i = 0 ; i < n ; i ++){
char lc , rc;
getchar();
scanf("%c %c" , &lc , &rc);
Node[i].lchild = strNum(lc);
Node[i].rchild = strNum(rc);
}
//find the root of tree
int root = find_root();
//Use the post Order to invert the tree
post_order(root);
//print the level order
BFS(root);
//make the num to 0
num = 0;
//print the in order
in_order(root);
return 0;
}