您的位置:首页 > 其它

怎样从顶部开始逐层打印二叉树结点数据?

2011-09-26 15:02 351 查看
 
//怎样从顶部开始逐层打印二叉树结点数据?

#include <iostream>

#include "stdlib.h"

#include <string>

#include <list>

#include <queue>

using namespace std;

typedef struct node {

        int value;

        struct node *lchild;

        struct node *rchild;

}Node,*Bintree;

queue<Node,list<Node> > q;

int i=0;

int mycount=3;

Bintree & createBintree(Bintree &p)

{

  p = (Bintree)malloc(sizeof(Node));

  p->value = ++i;

  if (--mycount>=0) {

    p->lchild = createBintree(p->lchild);

    p->rchild = createBintree(p->rchild);

  }

  else

  {

 p->lchild =NULL;

    p->rchild =NULL;

  }

  return p;

}

void BFSTraverse(Bintree T)

{

 Node a;

 if(T)q.push(*T);

 while(!q.empty())

 {

  a=q.front();

  cout<<a.value<<" ";

  q.pop();

  if(a.lchild)q.push(*a.lchild);

  if(a.rchild)q.push(*a.rchild);

 }

}

void display_tree(Bintree tree) {

 if(tree){     

   

 display_tree(tree->lchild);

 cout<<tree->value<<" ";

    display_tree(tree->rchild);

 }

}

int main() {

    static Bintree tree; 

 createBintree(tree);

 cout<<endl<<"中序遍历二叉树";

 display_tree(tree);

 cout<<endl<<"层序遍历二叉树";

    BFSTraverse(tree);

    return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  tree struct null
相关文章推荐