二叉树的前序线索化,寻找prior,next函数
#include<iostream>
using namespace std;
struct Threadnode
{
struct Threadnode *lchild, *rchild;
bool ltag, rtag;
};
Threadnode *pre;
void Thread(Threadnode *&root )//前序线索化
{
if (!root)
return;
else
{
if (!root->lchild)
{
root->lchild = pre;
root->ltag = 1;
}
if (!pre->rchild)
{
pre->rchild = root;
pre->rtag = 1;
}
pre = root;
Thread(root->lchild);
Thread(root->rchild);
}
}
void next(Threadnode *node, Threadnode *&x)
{
if (node->ltag)
x = node->rchild;
else
x = node->lchild;
}
void prior(Threadnode *bt,Threadnode *node, Threadnode *&x)
{
x = bt;
Threadnode *t;
if (node->ltag)
x = node->lchild;
else
{
while (x != node)
{
t = x;
next(t, x);
}
x = t;
}
}
int main()
{
system("pause");
return 0;
}
中序线索化与二叉树中序线索化寻找前驱和后继
#include<iostream>
using namespace std;
struct Threadnode
{
struct Threadnode *lchild, *rchild;
bool ltag, rtag;
};
Threadnode *pre;
void Thread(Threadnode *&root )//中序线索化
{
if (!root)
return;
else
{
Thread(root->lchild);
if (!root->lchild)
{
root->lchild = pre;
root->ltag = 1;
}
if (!pre->rchild)
{
pre->rchild = root;
pre->rtag = 1;
}
pre = root;
Thread(root->rchild);
}
}
void prior(Threadnode *node, Threadnode *&x)
{
if (node->ltag)
x = node->lchild;
else
{
x = node->lchild;
while (x->rchild)
x = x->rchild;
}
}
void next(Threadnode *node, Threadnode *&x)
{
if (node->rtag)
x = node->rchild;
else
{
x = node->rchild;
while (x->lchild)
x = x->lchild;
}
}
int main()
{
system("pause");
return 0;
}
二叉树后序线索化,prior,next函数
#include<iostream>
using namespace std;
struct Threadnode
{
struct Threadnode *lchild, *rchild;
bool ltag, rtag;
};
Threadnode *pre;
void Thread(Threadnode *&root )//后序线索化
{
if (!root)
return;
else
{
Thread(root->lchild);
Thread(root->rchild);
if (!root->lchild)
{
root->lchild = pre;
root->ltag = 1;
}
if (!pre->rchild)
{
pre->rchild = root;
pre->rtag = 1;
}
pre = root;
}
}
void prior(Threadnode *node, Threadnode *&x)
{
if (node->rtag)
x = node->lchild;
else
x = node->rchild;
}
void next(Threadnode *bt, Threadnode *node, Threadnode *&x)
{
x = bt;
Threadnode *t;
if (node->rtag)
x = node->rchild;
else
{
while (x != node)
{
t = x;
prior(t, x);
}
x = t;
}
}
int main()
{
system("pause");
return 0;
}