【C/C++】【用队列结构实现二叉树的层次遍历】

来源:互联网 发布:音量放大器软件 编辑:程序博客网 时间:2024/05/01 00:11

 


#include "OJ.h"
#include <string.h>
#include <stdio.h>

/*
Description 
         要求按照指定要求打印二叉树
Prototype
         int BiNodePrint(BiNode &head, char *result)
Input Param
         head   需要打印的二叉树头结点
Output Param
         result 打印出的字符串
Return Value
         0     成功
         -1     失败或其他异常
*/
int BiNodePrint(BiNode &head, char *result)
{
 /*在这里实现功能*/
 struct strqueue s;
 BiNode bn;
 int idx = 0, have_err = 0;

 if (!result)
  return -1;
 
 initqueue(&s);
 enqueue( &s,  &head );

 memset(result, 0x00, MAXSIZE);

 while( s.num>0 )
 {
  if ( !dequeue(&s, &bn ) )
  {
   have_err = 1;;
   break;
  }
  memcpy( result+idx, &(bn.data), sizeof(bn.data) );
  idx += sizeof(bn.data);
  
  if (bn.left)
  {
   enqueue( &s, bn.left );  
  }
  if (bn.right)
  {
   enqueue( &s, bn.right );  
  }
 }
 if (have_err)
  return -1;
 
 result[idx] = 0;

 
 //printf("result=[%s]\n", result);
   
 return 0;
}

 

bool initqueue(struct strqueue *s)  /* 初始化队列,返回0表示失败,返回1表示成功 */
{
 bool result = 0;
 int  i = 0;

 /* 代码在这里实现 */
 result = 0;
 if ( !s )
  return result;
 
 memset( s->queue, 0x00, sizeof(BiNode)*MAXSIZE );

 s->head = -1;
 s->tail = -1;
 s->num = 0;


 result = 1;
 return result;
}

bool enqueue(struct strqueue *s, BiNode *x) /* 进队列,返回0表示失败,返回1表示成功 */
{
 bool result = 0;

 /* 代码在这里实现 */
 result = 0;
 if ( !s )
  return result;
   
 if( s->num >= MAXSIZE )
  return result;

 memcpy( &(s->queue[s->tail = (s->tail+1) % MAXSIZE]), x, sizeof(BiNode) );
 s->num++;
 if(-1 == s->head)
  s->head = 0;

 result = 1;

 return result;
}

bool dequeue(struct strqueue *s, BiNode *x) /* 出队列,返回0表示失败,返回1表示成功 */
{
 bool result = 0;

 /* 代码在这里实现 */
 result = 0;
 if (!s)
  return result;
 
 if( s->num < 1 )
  return result;
 
 memcpy( x, &(s->queue[(s->head) % MAXSIZE]), sizeof(BiNode) );
 //s->queue[(s->head) % MAXSIZE] = 0;
 s->head = (s->head + 1) % MAXSIZE;
 //printf( "top =[%d], s->head=[%d]\n", *x, s->head );

 
 if ( 0 == (s->num = s->num - 1) )
 {
  s->head = -1;
  s->tail = -1;
 }

 result = 1;

 return result;
}

#ifndef __OJ_H__
#define __OJ_H__

#define MAXSIZE 100

typedef struct tagBiNode
{
    char             data;
    struct tagBiNode *left;
    struct tagBiNode *right;
} BiNode;


struct strqueue
{
 BiNode queue[MAXSIZE];
 int head; /* 队头 */
 int tail; /* 队尾 */
 int num;  /* 队元素个数 */
};


bool initqueue(struct strqueue *s);  /* 初始化队列,返回0表示失败,返回1表示成功 */
bool enqueue(struct strqueue *s, BiNode *x); /* 进队列,返回0表示失败,返回1表示成功 */
bool dequeue(struct strqueue *s, BiNode *x); /* 出队列,返回0表示失败,返回1表示成功 */

int BiNodePrint(BiNode &head, char *result);

#endif

 

 

 

0 0
原创粉丝点击