#include <iostream>
using namespace std;
struct BiNode
{
char data;
struct BiNode *lchild, *rchild;
};
BiNode* create(BiNode *bt)//创建二叉树
{
char x;
cin >> x;
if (x == '#')
{
bt = NULL;
}
else
{
bt = new BiNode;//???每次都要分配新的内存空间
bt->data = x;
bt->lchild=create(bt->lchild);
bt->rchild=create(bt->rchild);
}
return bt;
}
class Bitree
{
private:
BiNode *root;
public:
Bitree();
void Pre(BiNode *bt);
void In(BiNode *bt);
void Post(BiNode *bt);
};
Bitree::Bitree()
{
root=create(root);
Pre(root);
In(root);
Post(root);
}
void Bitree::Pre(BiNode *bt)
{
if (bt == NULL) return;
else
{
cout << bt->data;
Pre(bt->lchild);
Pre(bt->rchild);
}
}
void Bitree::In(BiNode *bt)
{
if (bt == NULL) return;
else
{
Pre(bt->lchild);
cout << bt->data;
Pre(bt->rchild);
}
}
void Bitree::Post(BiNode *bt)
{
if (bt == NULL) return;
else
{
Pre(bt->lchild);
Pre(bt->rchild);
cout << bt->data;
}
}
int main()
{
Bitree MyBitree;
return 0;
}
- create
运用递归创建
每次都返回bt
//最终版
BiNode* create(BiNode *bt)//创建二叉树
{
char x;
cin >> x;
if (x == '#')
{
bt = NULL;
}
else
{
bt = new BiNode;//???每次都要分配新的内存空间
bt->data = x;
bt->lchild=create(bt->lchild);
bt->rchild=create(bt->rchild);
}
return bt;
}
//当没有返回值的时候 根节点一直没有被改变 不能成功创建
void create(BiNode *bt)//创建二叉树
{
char x;
cin >> x;//create异常
if (x == '#')
{
bt = NULL; }
else
{
bt = new BiNode;
bt->data = x;
create(bt->lchild);
create(bt->rchild);
}
}
Tips:
1.注意判断x==‘#’
否则函数不能成功返回
2.
疑问 待整理
bt = new BiNode;//???每次都要分配新的内存空间