您的位置:首页 > 其它

【算法】输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印

2012-10-01 21:45 344 查看
题目:输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印。

例如输入

      8
    /  \
   6    10
  /\     /\
5  7   9  11

输出8   6   10   5   7   9   11。

思路是遍历一个结点时,首先访问它,然后将它的左右子树放入队列中。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <queue>
using namespace std;

typedef struct node
{
int key;
struct node *pleft;
struct node *pright;
}Node;

int CreateTreeByInsertData(Node **p,int k)//理解为什么用二级指针
{
if(*p==NULL)
{
*p=(Node *)malloc(sizeof(Node));
(*p)->key=k;
(*p)->pleft=(*p)->pright=NULL;
return 1;
}
else if(k == (*p)->key)
return 0;
else if(k < (*p)->key)
return CreateTreeByInsertData(&(*p)->pleft,k);
else
return CreateTreeByInsertData(&(*p)->pright,k);

}

void visitByLevel(Node *p)
{
queue<Node*> myQueue;
if(p == NULL)
return;
myQueue.push(p);
while(!myQueue.empty())
{
Node *now = myQueue.front();
myQueue.pop();
printf("%d ",now->key);
if(now->pleft) myQueue.push(now->pleft);
if(now->pright) myQueue.push(now->pright);
}
printf("\n");
}

void ClearTree(Node** tree)//删除树的操作,在本题中不一定用的到
{
if(*tree==NULL)return;
ClearTree(&(*tree)->pleft);
ClearTree(&(*tree)->pright);
free(*tree);
*tree=NULL;
}

int main()
{
int i;
Node *proot = NULL;

int data[] = {8,6,10,5,7,9,11};

//依次插入一些数据,创建一个二叉排序树
for(i=0; i<sizeof(data)/sizeof(int); i++)
CreateTreeByInsertData(&proot, data[i]);
visitByLevel(proot);

ClearTree(&proot);

return 0;
}


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