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

1222: 数据结构练习题——先序遍历二树  

TimeLimit(Common/Java):1000MS/10000MS    Memory Limit:65536KByte
Total Submit: 699        Accepted:379

Description

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

Input

输入数据分为多组,第一行是测试数据的组数n,下面的n行分别代表一棵二叉树。每棵二叉树的结点均为正整数,数据为0代表当前结点为空,数据为-1代表二叉树数据输入结束,-1不作处理。二叉树的构造按照层次顺序(即第11个整数,第22个,第34个,第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;
}   

 

 


 

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值