您的位置:首页 > 理论基础 > 数据结构算法

数据结构————二叉树的三种遍历

2014-04-14 19:21 260 查看
1222: 数据结构练习题——先序遍历二树

TimeLimit(Common/Java):1000MS/10000MS Memory Limit:65536KByte

Total Submit: 699 Accepted:379

Description

给定一颗二叉树,要求输出二叉树的深度以及先序遍历二叉树得到的序列。本题假设二叉树的结点数不超过1000。
Input

输入数据分为多组,第一行是测试数据的组数n,下面的n行分别代表一棵二叉树。每棵二叉树的结点均为正整数,数据为0代表当前结点为空,数据为-1代表二叉树数据输入结束,-1不作处理。二叉树的构造按照层次顺序(即第1层1个整数,第2层2个,第3层4个,第4层有8个......,如果某个结点不存在以0代替),比如输入:
1 2 0 3 4 -1得到的二叉树如下:
Output

输出每棵二叉树的深度以及先序遍历二叉树得到的序列。
Sample Input

2

1 -1

1 2 0 3 4 -1

Sample Output

1 1

3 1 2 3 4

Source

TOJ

#include<stdio.h>
#include<string.h>
#include<stack>
#include<stdlib.h>
typedef struct btnode
{
int data;
struct btnode *lchild,*rchild;
}Bitnode,*Bitree;
Bitnode *CreatBitree_level()//简历树
{
Bitnode *Q[1000];
int front = 1,rear = 0;
int ch;
Bitnode *root = NULL,*s;
while((scanf("%d",&ch)),ch!= -1)
{
if(ch == 0)
s = NULL;
else
{
s = (Bitnode*)malloc(sizeof(Bitnode));
s->data = ch;
s->lchild = NULL;
s->rchild = NULL;
}
Q[++rear] = s;
if(rear == 1)
root = s;
else
{
if(s&&Q[front])
if(rear%2==0)
Q[front]->lchild= s;
else
Q[front]->rchild = s;
if(rear%2 == 1)
front++;
}

}return root;
}

int depth(Bitnode *t)//求树的深度
{
int high,lhigh,rhigh;
if(!t)
high = 0;
else
{
lhigh = depth(t->lchild);
rhigh = depth(t->rchild);
if(lhigh > rhigh )
{
high = lhigh + 1;
}
else
high = rhigh + 1;
}
return high;
}
void preorder(Bitnode *t)//先序遍历
{
if(t)
{
printf(" %d",t->data);
preorder(t->lchild);
preorder(t->rchild);
}
}
int main()
{
int n,high;
Bitnode *t;
scanf("%d",&n);
while(n--)
{
t = CreatBitree_level();
high = depth(t);
printf("%d",high);
preorder(t);
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: