求解答,解答就采纳,感谢
typedef struct BiTNode
{
char data;
struct BiTNode *lchild, *rchild;
}BiTreeNode, *BiTree;
BiTree CreateBiTree(char str[100]);
void show(BiTree bt);
int main()
{
BiTree bt;
char str[100];
gets(str);
CreateBiTree(str);
show(bt);
return 0;
}
BiTree CreateBiTree(char str[])
{
BiTree bt;
static int i=0;
char c=str[i++];
if(c=='#') bt=NULL;
else
{
bt=(BiTree)malloc(sizeof(BiTreeNode));
bt->data=c;
bt->lchild=CreateBiTree(str);
bt->rchild=CreateBiTree(str);
}
return bt;
}
void show(BiTree bt)
{
if(bt)
{
show(bt->lchild);
printf("%c",bt->data);
show(bt->rchild);
}
}
else里你要把bt连到之前的节点上啊,你这孤零零new了个bt出来,然后没有任何节点在子节点是bt,你不是白new了吗
#include <iostream>
using namespace std;
#include <queue>
class Node
{
public:
char data;
Node* lchild; //指向左孩子
Node* rchild; //指向右孩子
};
using Tree = Node*;
void CreateTree(Tree& t)
{
char c;
cin >> c;
if (c == '#')
{
t = nullptr; //没有结点就空指
}
else //创建新结点
{
t = new Node;
t->data = c;
CreateTree(t->lchild);
CreateTree(t->rchild);
}
}
//先序遍历
void DLR(const Tree& t)
{
cout << t->data << " ";
if (t->lchild)
{
DLR(t->lchild);
}
if (t->rchild)
{
DLR(t->rchild);
}
}
//中序遍历
void LDR(const Tree& t)
{
if (t->lchild)
{
LDR(t->lchild);
}
cout << t->data << " ";
if (t->rchild)
{
LDR(t->rchild);
}
}
//后序遍历
void LRD(const Tree& t)
{
if (t->lchild)
{
LRD(t->lchild);
}
if (t->rchild)
{
LRD(t->rchild);
}
cout << t->data << " ";
}
//层次遍历
void Gradation(const Tree& t)
{
queue<Node*> q; //存的是指针不是结点
q.push(t); //先把树根的指针入队
Node* temp = nullptr;
while (!q.empty())
{
temp = q.front();
q.pop();
cout << temp->data << " ";
if (temp->lchild)
{
q.push(temp->lchild);
}
if (temp->rchild)
{
q.push(temp->rchild);
}
}
}
int main()
{
Tree my_tree;
int choose = 0;
cout << "请选择要执行的操作" << endl;
cout << "1、创建二叉树" << endl;
cout << "2、先序遍历" << endl;
cout << "3、中序遍历" << endl;
cout << "4、后序遍历" << endl;
cout << "5、层次遍历" << endl;
cout << "0、退出" << endl;
while (cin >> choose)
{
switch (choose)
{
case 1:
cout << "请输入要创建树的先序序列,结点没有孩子的位置用#代替:" << endl;
CreateTree(my_tree);
cout << endl;
break;
case 2:
cout << "先序遍历:" << endl;
DLR(my_tree);
cout << endl;
break;
case 3:
cout << "中序遍历:" << endl;
LDR(my_tree);
cout << endl;
break;
case 4:
cout << "后序遍历:" << endl;
LRD(my_tree);
cout << endl;
break;
case 5:
cout << "层次遍历:" << endl;
Gradation(my_tree);
cout << endl;
break;
case 0:
cout << "Bye-Bye" << endl;
return 0;
default:
break;
}
cout << "请输入下一个指令" << endl;
}
return 0;
}