Description
给定一颗二叉树,要求输出二叉树的深度以及中序遍历二叉树得到的序列。本题假设二叉树的结点数不超过1000。
Input
输入数据分为多组,第一行是测试数据的组数n,下面的n行分别代表一棵二叉树。每棵二叉树的结点均为正整数,数据为0代表当前结点为空,数据为-1代表二叉树数据输入结束,-1不作处理。二叉树的构造按照层次顺序(即第1层1个整数,第2层2个,第3层4个,第4层有8个……,如果某个结点不存在以0代替)
Output
输出每棵二叉树的深度以及中序遍历二叉树得到的序列。
Sample Input
2
1 -1
1 2 0 3 4 -1
Sample Output
1 1
3 3 2 4 1
例如样例二
/*建树的时候,是按照层次顺序来构造
即构造完根节点之后,去构造他的左右孩子节点
根节点序号为 x
左孩子节点是 2*x 右孩子节点是 2*x+1
*/
#include<stdio.h>
#include<string.h>
#include<cstring>
#include<stdlib.h>
#include<iostream>
#include<queue>
using namespace std;
char c;
int flag;
int s[1001];
typedef struct BiTNode
{
int data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
void CreateBiTree(BiTree &T,int a)//a 是节点序号
{
if(a>flag||s[a]==0){//根节点不存在的情况
T=NULL;
return;
}
T=(BiTree)malloc(sizeof(BiTNode));//开辟节点空间
T->data=s[a];
CreateBiTree(T->lchild,2*a);
CreateBiTree(T->rchild,2*a+1);
}
void Inorder(BiTree T)
{
if(T!=NULL)
{
Inorder(T->lchild);
printf("% d",T->data);
Inorder(T->rchild);
}
}
int TreeDepth(BiTree T)//求树的高度
{
int r,l;
if(T==NULL)
return 0;
else{
l=TreeDepth(T->lchild)+1;//加1 是加的一个根结点
r=TreeDepth(T->rchild)+1;
}
return (l>r?l:r);//返回一个最大的是
}
int main()
{
int n,depth=0;
scanf("%d",&n);
while(n--)
{
flag=1;
memset(s,0,sizeof(s));
while(scanf("%d",&s[flag])!=EOF)
{
if(s[flag]==-1)
break;
else
flag++;
}
flag--;
BiTree T;
CreateBiTree(T,1);
depth=TreeDepth(T);
printf("%d",depth);
Inorder(T);
printf("\n");
}
}