题目描述
老师有一个问题想考考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;
}