一. 线索二叉树的创建、遍历
运行结果
代码如下,注释为王
#include<iostream>
typedef struct TBTNode {
int data;
int ltag, rtag;
struct TBTNode* lchild;
struct TBTNode* rchild;
TBTNode() :data(0), ltag(0), rtag(0), lchild(0), rchild(0) {}
TBTNode(int _data) :data(_data), ltag(0), rtag(0) {
this->lchild = this->rchild = 0;
}
} TBTNode;
int BSTInsert(TBTNode*& bt, int key) {
if (bt == 0) {
bt = new TBTNode;
bt->lchild = bt->rchild = 0;
bt->data = key;
return 1;
}
else {
if (key == bt->data) return 0;
else if (key < bt->data)
return BSTInsert(bt->lchild, key);
else
return BSTInsert(bt->rchild, key);
}
}
void CreateBST(TBTNode*& bt, int key[], int n) {
bt = 0;
for (int i = 0; i < n; ++i) {
BSTInsert(bt, key[i]);
}
}
void InThread(TBTNode* p, TBTNode*& pre) {
if (p != 0) {
InThread(p->lchild, pre);
if (p->lchild == 0) {
p->lchild = pre;
p->ltag = 1;
}
if (pre != 0 && pre->rchild == 0) {
pre->rchild = p;
pre->rtag = 1;
}
pre = p;
InThread(p->rchild, pre);
}
}
void createInThread(TBTNode* root) {
TBTNode* pre = 0;
if (root != 0) {
InThread(root, pre);
pre->rchild = 0;
pre->rtag = 1;
}
}
void inOrder(TBTNode* p) {
if (!p) return;
inOrder(p->lchild);
std::cout << p->data << '\t';
inOrder(p->rchild);
}
TBTNode* First(TBTNode* p) {
while (p->ltag == 0) p = p->lchild;
return p;
}
TBTNode* Next(TBTNode* q) {
if (q->rtag == 0) return First(q->rchild);
else return q->rchild;
}
void Inorder(TBTNode* root) {
auto p = First(root);
while (p != nullptr) {
std::cout << p->data << '\t';
p = Next(p);
}
std::cout << std::endl;
}
int main() {
int key[]{ 5,2,6,8,7,9,3 };
std::cout << "打印测试数组:\n";
for (auto& i : key) {
std::cout << i << '\t';
}
std::cout << '\n';
TBTNode* root = new TBTNode;
CreateBST(root, key, sizeof(key) / sizeof(key[0]));
std::cout << "递归中序遍历二叉排序树应为递增序列:\n";
inOrder(root);
std::cout << '\n';
createInThread(root);
std::cout << "遍历线索二叉排序树也应为递增序列:\n";
Inorder(root);
system("pause");
return 0;
}
二. 前、后序递归线索化二叉树(补充)
都和中序线索化代码极为相似
void preThread(TBTNode* p, TBTNode*& pre) {
if (p != 0) {
if (p->lchild == 0) {
p->lchild = pre;
p->ltag = 1;
}
if (pre != 0 && pre->rchild == 0) {
pre->rchild = p;
pre->rtag = 1;
}
pre = p;
if(p->ltag == 0) preThread(p->lchild, pre);
if(p->rtag == 0) preThread(p->rchild, pre);
}
}
void postThread(TBTNode* p, TBTNode*& pre) {
if (p != 0) {
postThread(p->lchild, pre);
postThread(p->rchild, pre);
if (p->lchild == 0) {
p->lchild = pre;
p->ltag = 1;
}
if (pre != 0 && pre->rchild == 0) {
pre->rchild = p;
pre->rtag = 1;
}
pre = p;
}
}
|