描述:给一个二叉树。把二叉树按照层数来打印。如果为相同层,则从左到右打印。
输入:首先输入一个整数T,表示一共有T组数据 0<T<=10再输入两个整数N,M(0<=N,M<=100);表示下面有N行,这个树有M个节点(1号节点是这棵树的根节点);每一行两个整数a,b(1<=a,b<=M);表示节点a的父亲是节点b。
1 #include <iostream> 2 #include<stdio.h> 3 #include<queue> 4 using namespace std; 5 6 struct BiTree{ 7 int id,depth; 8 struct BiTree *lchild,*rchild; 9 }; 10 11 struct BiTree tree[101]; 12 13 int main() 14 { 15 int T; 16 cin >> T; 17 int t=T; 18 while(T--){ 19 int N,M; 20 cin >> N; 21 cin >> M; 22 for(int i=1;i<=M;i++){//初始化 23 tree[i].id=i; 24 tree[i].depth=0; 25 tree[i].lchild=tree[i].rchild=NULL; 26 } 27 tree[1].depth=1; 28 while(N--){ 29 int a,b; 30 scanf("%d%d",&a,&b); 31 if(!tree[a].lchild)//a加成b的左子树 32 tree[a].lchild=&tree[b]; 33 else//a加成b的右子树 34 tree[a].rchild=&tree[b]; 35 tree[b].depth=tree[a].depth+1;//深度加一 36 } 37 printf("Q%d:\n",t-T); 38 queue<BiTree*> Q; 39 Q.push(&tree[1]); 40 int level=0; 41 BiTree *temp; 42 while(!Q.empty()){ 43 temp=Q.front(); 44 Q.pop(); 45 if(temp->depth==level) 46 printf("%d",temp->id); 47 else{ 48 level++; 49 printf("\n%d",temp->id); 50 } 51 if(temp->lchild) 52 Q.push(temp->lchild); 53 if(temp->rchild) 54 Q.push(temp->rchild); 55 } 56 printf("\n"); 57 } 58 return 0; 59 }
5230

被折叠的 条评论
为什么被折叠?



