【北邮OJ】100. 二叉树的层数

题目描述
老师有一个问题想考考mabo,但是mabo不会,所以想请你来帮帮忙。

问题如下:

给一个二叉树

请把这个棵二叉树按层来打印。如果为相同层,需要从左到右打印。一个节点是先添加左节点后添加右节点,即添加顺序与输入顺序一致。

输入格式
首先输入一个整数T,表示一共有T组数据 0 < T<=10

再输入两个整数N,M(0<=N,M<=100)

表示下面有N行,这个树有M个节点(1号节点是这棵树的根节点)

每一行两个整数a,b(1<=a,b<=M)

表示节点a的父亲是节点b

输出格式
对于每组

先输出一行 “Qi:”表示第i个问题

然后接下来输出每个问题二叉树每层的节点,在同一层的节点用空格分开,同一层输出在一行(每一行末尾没有空格),不同的层输出在不同行(入下面Sample Ouput所示)

总结:
1。应按层序遍历打印,待修改
2。changedeep()递归,类似深度遍历,可用
3。每一行末尾没有空格的处理方法

#include <stdio.h>
#include <iostream>
using namespace std;

struct node{
    int child1;
    int child2;
    int deep;
}tree[100];

void treeinit(node tree[]){
    int i;
    for(i=0;i<=100;i++){
        tree[i].child1 = 0;
        tree[i].child2 = 0;
        tree[i].deep = 0;
    }
    tree[1].deep = 1;
}

void changedeep(node tree[],int i){
    if(tree[i].child1 != 0){
        int j;
        j=tree[i].child1;
        tree[j].deep = tree[i].deep+1;
        changedeep(tree,j);
    }
    if(tree[i].child2 != 0){
        int j;
        j=tree[i].child2;
        tree[j].deep = tree[i].deep+1;
        changedeep(tree,j);
    }
}

int main(){
    int t,T;
    cin>>T;
    for(t=1;t<=T;t++){
        int n,N;
        int m,M;
        int parent,child;
        cin>>N;
        cin>>M;
        treeinit(tree);
        for(n=1;n<=N;n++){
            cin>>child;
            cin>>parent;
            if(tree[parent].child1 == 0)
                tree[parent].child1 = child;
            else tree[parent].child2 = child;
        }
        changedeep(tree,1);
        int i,d,maxdeep;
        for(i=1;i<=M;i++){
            if(tree[i].deep>tree[i-1].deep)
                maxdeep = tree[i].deep;
        }
        for(d=1;d<=maxdeep;d++){
            int flag=0;
            for(i=1;i<=M;i++){
                if(d == tree[i].deep && flag != 0)
                    cout<<" "<<i;
                if(d == tree[i].deep && flag == 0){
                    cout<<i;
                    flag = 1;
                }

            }
            cout<<endl;
        }              
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值