急求层次遍历建立二叉树的算法

miraculous16 2006-03-22 08:48:54
按完全二叉树的层次顺序,依次输入结点信息来建立二叉链表
...全文
315 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
miraculous16 2006-03-23
  • 打赏
  • 举报
回复
谢谢各位
Rick_ang 2006-03-23
  • 打赏
  • 举报
回复
层次遍历用队列
bombwang 2006-03-23
  • 打赏
  • 举报
回复
mark
du51 2006-03-22
  • 打赏
  • 举报
回复
#include <iostream>
#include <cstdlib>

using namespace std;

struct BinTree
{
int data;
BinTree *Left,*Right;
};

void del(BinTree *p)
{
if(p->Left)del(p->Left);
if(p->Right)del(p->Right);
delete p;
}
BinTree *Creat(int *node, int &size, int pos)
{

if(pos>=size) return NULL;
BinTree *t = new BinTree;
t->data=node[pos];
t->Left=Creat(node, size, pos*2+1);
t->Right=Creat(node, size, pos*2+2);
return t;
}

void DFS( BinTree*p)
{
if(!p)return ;
cout<<p->data<<" ";
DFS(p->Left);
DFS(p->Right);
}

int main(int argc, char *argv[])
{
BinTree *tree;
int node[]={\
1,2,3,4,5,6,7,8,9,10,11,12,\
13,45,15,16,17,18,19,20,21,\
22,23,24,25,26,27,28,29,30,31
};
int size=sizeof(node)/sizeof(node[0]);
tree=Creat(node, size, 0);
DFS(tree);
printf("\n") ;
del(tree);
system("PAUSE");
return 0;
}
benlei999 2006-03-22
  • 打赏
  • 举报
回复
我写了一个
#include "stdafx.h"
#include <iostream.h>
#include <QUEUE>
using namespace std;
struct Node
{
char data[20];
struct Node* left;
struct Node* right;
};

void CreateTree(Node *head,char *endChar)//endChar是结束输入的字符串
{
queue<Node *> que;
char str[20]="";
cin>>str;
if (strcmp(str,endChar))
{
strcpy(head->data,str);
head->left=NULL;
head->right=NULL;
que.push(head);
}
else
{
return;
}
cin>>str;
while(strcmp(str,endChar))
{

Node *p=new Node;
strcpy(p->data,str);
p->left=NULL;
p->right=NULL;

if (que.front()->left==NULL)
que.front()->left=p;
else
{
que.front()->right=p;
que.pop();
}
que.push(p);
cin>>str;
}
}
void DisplayTree(Node *head)
{
queue<Node *> que;
que.push(head);
while(que.size()!=0)
{
Node *p=que.front();
if (p!=NULL)
{
cout<<p->data<<" ";
que.push(p->left);
que.push(p->right);
}
que.pop();
}
cout<<endl;
}
void main()
{
Node tree;
CreateTree(&tree,"end");
DisplayTree(&tree);
}
miraculous16 2006-03-22
  • 打赏
  • 举报
回复
怎么存啊,我不会啊,这位大狭教教我吧!
benlei999 2006-03-22
  • 打赏
  • 举报
回复
晕,用队列存左右节点的指针
benlei999 2006-03-22
  • 打赏
  • 举报
回复
用递归很容易搞定的

65,210

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧