pat甲级1102. Invert a Binary Tree (25)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/richenyunqi/article/details/80151159

欢迎访问我的pat甲级题解目录哦https://blog.csdn.net/richenyunqi/article/details/79958195

1102. Invert a Binary Tree (25)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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.

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.

Sample Input:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
Sample Output:
3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1

题意分析:

给出N个结点的左右子树孩子节点的编号,将该树翻转(即每个结点的左右子树都做一次交换),输出翻转后的二叉树的层序遍历序列和中根遍历序列。

算法设计:

这道题用静态写法更方便。既然要输出翻转之后的二叉树,可以在读取左右子树结点时先读入右子树,再读入左子树来实现翻转。主要问题在于如何找到根结点,很明显根结点不是任何结点的子树,可以定义一个长度为N的bool类型数组child,元素均初始化为false,然后在读取子树结点时,将child数组相应位置的元素设为true,读取完成后遍历整个child数组,元素仍为false的下标即为根结点的编号。

c++代码:

#include<bits/stdc++.h>
using namespace std;
struct Node{//结点类,没有数据域
    int left=-1,right=-1;
};
Node tree[10];
void inOrder(int root,bool&space){//中根遍历,space指示输出数字之前是否需要输出空格
    if(root==-1)//root==-1,直接返回
        return;
    inOrder(tree[root].left,space);//递归遍历左子树
    printf("%s%d",space?" ":"",root);//输出
    space=true;//已经输出过,以后都需要输出空格,置false为true
    inOrder(tree[root].right,space);//递归遍历右子树
}
void levelOrder(int root){//层次遍历
    queue<int>q;
    q.push(root);
    while(!q.empty()){
        int t=q.front();
        q.pop();
        printf("%s%d",t==root?"":" ",t);//不是根节点的输出前都需输出一个空格
        if(tree[t].left!=-1)
            q.push(tree[t].left);
        if(tree[t].right!=-1)
            q.push(tree[t].right);
    }
}
int main(){
    int N;
    scanf("%d",&N);
    bool child[N]={false};
    for(int i=0;i<N;++i){
        char a,b;
        scanf("\n%c %c",&a,&b);
        if(a!='-'){
            tree[i].right=a-'0';
            child[a-'0']=true;
        }
        if(b!='-'){
            tree[i].left=b-'0';
            child[b-'0']=true;
        }
    }
    int root=find(child,child+N,false)-child;//仍为false的下标为根节点标号
    levelOrder(root);
    printf("\n");
    bool space=false;
    inOrder(root,space);
    return 0;
}

阅读更多

扫码向博主提问

日沉云起

用最短的代码,写最快的算法
  • 擅长领域:
  • 算法
去开通我的Chat快问
换一批

没有更多推荐了,返回首页