中序线索化链表

来源:互联网 发布:js取1到10随机数 编辑:程序博客网 时间:2024/05/23 19:43
#include<iostream>
using namespace std;
//enum falg{child,thread};
struct biNode
{
char data;
biNode* lchild, *rchild;
int ltag, rtag;
};
class tree
{
public:
tree();
biNode *next(biNode* p);
void inorder();
private:
biNode *root,*q;
biNode* create(biNode* bt);//输入二叉树的数据信息
//按照书本写的(即传递两个参数)现右子树的线索化不成功
void intree(biNode *bt);//遍历设置左右两个标志
};
biNode* pre=NULL;
char ch;
biNode* tree::create(biNode *bt)
{
cin >> ch;
if (ch == '#')
bt = NULL;
else
{
bt = new biNode;
bt->data = ch;
bt->ltag = 0;
bt->rtag = 0;
bt->lchild = create(bt->lchild);
bt->rchild = create(bt->rchild);
}
return bt;
}
void tree::intree(biNode *bt)
{
if (bt == NULL)
return;
intree(bt->lchild);//遍历左子树
if (bt->lchild == NULL)
{
bt->ltag = 1;
bt->lchild = pre;
}
if (bt->rchild == NULL)
bt->rtag = 1;
if (pre != NULL)//因为pre的初始值是NULL因此要先判断pre是否为空
{
if (pre->rtag == 1)
pre->rchild = bt;
}
pre = bt;
intree(bt->rchild);//遍历右子树
}
biNode* tree::next(biNode* p)
{
if (p->rtag == 1)
q = p->rchild;
else
{
q = p->rchild;
while (q->ltag == 0)
q = q->lchild;
}
return q;
}
tree::tree()
{
root = create(root);
intree(root);
}
void tree::inorder()
{
if (root == NULL)
return;
q = root;
while (q->ltag == 0)
q = q->lchild;
cout << q->data;
while (q->rchild != NULL)
{
q = next(q);
cout << q->data;
}
cout << endl;
}
void main()
{
tree tree;
tree.inorder();

}


0 0
原创粉丝点击