建议你深入学习C语言的指针部分
这样应该就可以了吧#include<iostream>
#include<string>
template <class T>
struct treenode
{
T data;
bool ltag;
bool rtag;
treenode<T> *lchild;
treenode<T> *rchild;
};
template <class T>
class BinaryTree
{
public:
BinaryTree();
~BinaryTree();
void middle(treenode<T> *t);
void clue();
private:
void createtree(treenode<T> **t);
treenode<T> *head, *pre, *p, *t;
T c;
};
template<class T>
BinaryTree<T>::BinaryTree()
{
createtree(&t);
clue();
}
template<class T>
BinaryTree<T>::~BinaryTree()
{
}
template<class T>
void BinaryTree<T>::middle(treenode<T> *t)
{
if(t)
{
middle(t->lchild);
if(!t->lchild)
{
t->ltag = 1;
t->lchild = pre;
}
if(!pre->rchild)
{
pre->rtag = 1;
pre->rchild = t;
}
pre = t;
middle(t->rchild);
}
}
template<class T>
void BinaryTree<T>::clue()
{
treenode<T> *s = new treenode<T>;
s->ltag = 0;
s->rtag = 1;
s->rchild = head;
if(!head)
{
s->lchild = s;
}
else
{
s->lchild = head;
pre = s;
middle(head);
pre->rchild = p;
pre->rtag = 1;
s->rchild = pre;
}
}
int mbf = 1;//我是实在没办法才搞了这个东西,它存在的目的是为了让93行的if只在开始的时候执行一次
template<class T>
void BinaryTree<T>::createtree(treenode<T> **t)
{
std::cin >> c;
if('#' == c)
{
*t = NULL;
}
else
{
*t = new treenode<T>;
if(mbf == 1)
{
head = *t;
mbf--;
}
(*t)->data = c;
(*t)->ltag = 0;
(*t)->rtag = 0;
createtree(&(*t)->lchild);
createtree(&(*t)->rchild);
}
}
int main(void)
{
BinaryTree<char> shu;
return 0;
}
另外参考这个代码
这是百度的#include <cstdio>
#include <cstdlib>
#define ElemType char
//节点声明,数据域、左孩子指针、右孩子指针
typedef struct BiTNode {
char data;
struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;
//先序建立二叉树
BiTree CreateBiTree() {
char ch;
BiTree T;
scanf("%c", &ch);
if(ch == '#')T = NULL;
else {
T = (BiTree)malloc(sizeof(BiTNode));
T->data = ch;
T->lchild = CreateBiTree();
T->rchild = CreateBiTree();
}
return T;//返回根节点
}
//先序遍历二叉树
void PreOrderTraverse(BiTree T) {
if(T) {
printf("%c", T->data);
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
}
}
//中序遍历
void InOrderTraverse(BiTree T) {
if(T) {
PreOrderTraverse(T->lchild);
printf("%c", T->data);
PreOrderTraverse(T->rchild);
}
}
//后序遍历
void PostOrderTraverse(BiTree T) {
if(T) {
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
printf("%c", T->data);
}
}
int main(void) {
BiTree T;
T = CreateBiTree();//建立
PreOrderTraverse(T);//输出
return 0;
}
|