线索二叉树C++代码

线索二叉树,是将一个二叉树叶子节点未使用到的指针,指向中序遍历结果当中的前一个节点或后一个节点。

这样在进行中序遍历的时候,就无需用递归的方法,只需线性即可中序遍历。


下面先建立一个基本的二叉树

下面开始中序遍历线索化

下面开始线性中序遍历

完整代码


​#include <iostream>
#include <string>
using namespace std;

struct DataNode {char s;};
enum PointerTag {Link,Thread};
typedef struct BiThrNode {
	DataNode data;
	struct BiThrNode *lchild, *rchild;
	PointerTag ltag, rtag;
}BiThrNode, *BiThrTree;
BiThrTree pre;

void CreatBiTree(BiThrTree &tree, string str, int length, int index) {
	if (index <= length) {
		tree = (BiThrTree)malloc(sizeof(BiThrNode));
		DataNode Data;
		Data.s = str.at(index-1);
		tree->data = Data;
		tree->lchild = NULL;
		tree->rchild = NULL;
		tree->ltag = Link;
		tree->rtag = Link;
		CreatBiTree(tree->lchild, str, length, 2 * index);
		CreatBiTree(tree->rchild, str, length, 2 * index + 1);
	}
}

void InThreading(BiThrTree tree) {
	if (tree) {
		if (tree->lchild)InThreading(tree->lchild);

		if (!tree->lchild) {             //叶子节点的左边是pre节点,将它指向中序遍历的前一个节点(1)
			tree->ltag = Thread;
			tree->lchild = pre;
		}
		if (pre != NULL && !pre->rchild) { //执行与(1)相反的操作
			pre->rtag = Thread;
			pre->rchild = tree;
		}
		pre = tree;                        //保存当前节点为pre,以便中序遍历下一节点使用

		if (tree->rchild)InThreading(tree->rchild);
	}
}

void InOrderThreading(BiThrTree tree) {
	BiThrTree p = tree;
	while (p) {
		while (p->ltag == Link) {
			p = p->lchild;
		}
		cout << p->data.s << " ";
		while (p->rtag == Thread && p->rchild != NULL) {
			p = p->rchild;
			cout << p->data.s << " ";
		}
		p = p->rchild;
	}
}

int main()
{
	BiThrTree tree=NULL;
	string s;
	s = "ABCDEFG";
	CreatBiTree(tree, s, s.length(), 1);
	//flr(tree);
	InThreading(tree);
	InOrderThreading(tree);
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值