1102 Invert a Binary Tree (25 分)

输入规格:

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.

每个输入文件包含一个测试用例。对于每种情况,第一行给出一个正整数ñ (≤10),即树中节点的总数-因此,节点的编号从0到 − 1。然后ñ 后面跟随着几行,每行对应一个从0到 − 1,并给出该节点左右子节点的索引。如果孩子不存在,-则将a放置在该位置。任何一对孩子之间都用空格隔开。

输出规格:

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.

对于每个测试用例,在第一行中打印层级顺序(注意!!!这个是镜像二叉树的顺序!!),然后在第二行中打印倒置树的有序遍历序列。相邻数字之间必须恰好有一个空格,并且在行尾不能有多余的空格。

样本输入:

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

样本输出:

3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1

分析: 感谢这个老师提供了代码,我可算是明白了

1. 结构体struct node{int l,r}node[10]; l存本节点的左孩子的下标,r存本节点的右孩子的下标,若无左、右孩子,则存-1.

2. check[10]数组用来存每个结点有无父结点:无父结点的节点即为二叉树的顶点~

3. 用BFS遍历层,从二叉树的顶点开始把结点放入queue,然后在queue中加入该结点的子节点(先加入右节点,再加入左节点!!!),然后打印该节点并把该节点出队,直到queue为空while(!q.empty()){ ······ }

4. 输出镜像二叉树的中序遍历结果,是一个递归的过程。从二叉树的顶点开始,先遍历右子树,再遍历左子树。

代码:

#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
struct binarynode{
    int l,r;
}node[10];
int n,check[10],head,cnt;//check数组标记有父节点的结点
void in_order(int h){
	if(h==-1) return;
	in_order(node[h].r);
	cnt++;
	if(cnt==n) cout<<h<<endl;
	else cout<<h<<" ";
	in_order(node[h].l);
}
int main(){
    scanf("%d",&n);//二叉树的结点总数
    /* 创建二叉树 */
    for(int i=0;i<n;i++){
        string left,right;
        cin>>left>>right;
        if(left!="-"){
            node[i].l=stoi(left);
            check[stoi(left)]=1;
        }
        else node[i].l=-1;   //-1表示没有对应子结点
        if(right!="-"){
            node[i].r=stoi(right);
            check[stoi(right)]=1;
        }
        else node[i].r=-1;
    }
    /* 找根节点 */
    for(int i=0;i<n;i++)
        if(check[i]==0){
            head=i;
            break;
        }
    /* level-order */
    queue<int> q;
    q.push(head);
    int flag=0;
    while(!q.empty()){  //当队列为空的时候就停下来,队列为空时(队列中的元素全都被pop()了)
        int a=q.front();
        /* 因为是镜像输出每层的节点 */
        if(node[a].r!=-1) q.push(node[a].r);
        if(node[a].l!=-1) q.push(node[a].l);
        if(!flag){      // 避免树只有一个节点时打印节点后有个空格导致测试点通不过 ~
            flag=1;
            cout<<a;
        }else cout<<" "<<a;
        q.pop();//队列首节点出队
    }cout<<endl;
    /* 镜像-in-order */
    in_order(head);
    return 0;
}
/*
in-order traversal sequences of the inverted tree
倒排树的有序遍历序列,其实就是把二叉树镜像后输出它的中序序列
*/

第一次接触PAT甲级有关二叉树的题目,真是学到了!

猜你喜欢

转载自blog.csdn.net/WKX_5/article/details/114550545