全部代码
#include <iostream>
#include <stdlib.h>
using namespace std;
class Tree
{
public:
Tree();
Tree* malloc_node();
int free_node(Tree*&);
int create(Tree*&);
int midorder(Tree*);
int mid_club(Tree*);
int insert_head(Tree*);
int print_club();
private:
int number;
Tree *lchild, *rchild;
int ltag, rtag;
};
Tree *pre = NULL; //记录线索化二叉树的时候刚刚访问过的节点
Tree *head = NULL; //线索化后做链表头指针 里面记录节点总数 根据遍历顺序不同head的左右孩子也不同
int main()
{
Tree *root = NULL;
root->create(root);
root->midorder(root);
root->insert_head(root);
root->print_club();
return 0;
}
Tree::Tree() : number(-9999), lchild(NULL), rchild(NULL), ltag(0), rtag(0)
{
;
}
Tree* Tree::malloc_node()
{
return new Tree;
}
int Tree::free_node(Tree *&node)
{
delete node;
node = NULL;
return 0;
}
int Tree::create(Tree *&node)
{
int number = 0;
cout << "请输入节点数据:" << endl;
cin >> number;
if (number == -1)
{
cout << "返回上层成功" << endl;
return 0;
}
node = malloc_node();
node->number = number;
cout << "目前位置为" << number << "的左子树,";
create(node->lchild);
cout << "目前位置为" << number << "的右子树,";
create(node->rchild);
return 0;
}
int Tree::midorder(Tree *node)
{
if (!node)
{
return 0;
}
midorder(node->lchild);
cout << "中序遍历结果为:" << node->number << endl;
midorder(node->rchild);
return 0;
}
int Tree::insert_head(Tree *node)
{
head = head->malloc_node();
pre = head;
head->ltag = 1;
head->lchild = node;
mid_club(node);
pre->rtag = 1;
pre->rchild = head;
head->rchild = pre;
return 0;
}
int Tree::mid_club(Tree *node)
{
if (node)
{
mid_club(node->lchild);
if (!node->lchild)
{
node->ltag = 1;
node->lchild = pre;
}
if (!pre->rchild)
{
pre->rtag = 1;
pre->rchild = node;
}
pre = node;
mid_club(node->rchild);
}
return 0;
}
int Tree::print_club()
{
Tree *p = head->lchild;
while (p != head)
{
while (p->ltag == 0)
{
p = p->lchild;
}
cout << "树转换为循环双向链表后的数据为:" << p->number << endl;
while (p->rtag == 1 && p->rchild != head)
{
p = p->rchild;
cout << "树转换为循环双向链表后的数据为:" << p->number << endl;
}
p = p->rchild;
}
return 0;
}