您的位置:首页 > 其它

PAT A1102 Invert a Binary Tree 反转二叉树[二叉树静态写法 后序遍历反转二叉树]

2019-01-09 10:04 225 查看

The following is from Max Howell @twitter: 

[code]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.

第一行显示反转后的二叉树的层次遍历,第二行中序遍历,相邻数字之间用空格隔开,最后一个数字后面没有空格

[code]#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;
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐