二叉树线索化

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

typedef struct Node {
	int key;
	int ltag, rtag;//tag=1时建立线索,tag=0时为原遍历
	struct Node* lchild, * rchild;
}Node;

Node* getNewNode(int key) {
	Node *p = (Node*)malloc(sizeof(Node));
	p->key = key;
	p->lchild = p->rchild = NULL;
	p->ltag =p-> rtag = 0;
	return  p;


}

Node* insert(int key, Node* root) {
	if (root == NULL)return getNewNode(key);
	if (rand() % 2)root->lchild = insert(key, root->lchild);
	else root->rchild = insert(key, root->rchild);
	return root;


}
void pre_order(Node* root) {
	if (root == NULL)return;
	printf("%3d", root->key);
	if(root->ltag==0) pre_order(root->lchild);
	if (root->rtag == 0) pre_order(root->rchild);
	 return;

}

void in_order(Node* root) {
	if (root == NULL)return;
	
	if (root->ltag == 0)in_order(root->lchild);
	printf("%3d", root->key);
	if (root->rtag == 0)in_order(root->rchild);
	return;

}
void post_order(Node* root) {
	if (root == NULL)return;

	if (root->ltag == 0)post_order(root->lchild);
	if (root->rtag == 0)post_order(root->rchild);
	printf("%3d", root->key);
	return;

}
Node* pre_Node = NULL;
Node *inorder_root = NULL;

void __build_inorder_thread(Node* root) {
	if (root == NULL)return;

	if (root->ltag == 0)__build_inorder_thread(root->lchild);
	if (inorder_root == NULL)inorder_root = root;
	if (root->lchild == NULL) {
		root->lchild == pre_Node;
		root->ltag = 1;
	}
	if (pre_Node && pre_Node->rchild == NULL) {
		pre_Node->rchild = root;
		pre_Node->rtag = 1;

	}
	pre_Node = root;
	if (root->rtag == 0)__build_inorder_thread(root->rchild);
	return;
}
void build_inorder_thread(Node* root) {
	__build_inorder_thread(root);
	pre_Node->rchild = NULL;
	pre_Node->rtag = 1;
	return;

}
void clear(Node* root) {
	if (root == NULL)return;
	clear(root->lchild);
	clear(root->rchild);
	free(root);
	return;

}
Node* getNext(Node* root) {
	if (root->rtag == 1)return root->rchild;
	root = root->rchild;
	while (root->ltag == 0 && root->lchild)root = root->lchild;
	return root;
}
int main() {
	srand(time(0));
	Node* root = NULL;
	for (int i=0; i < MAX_OP; i++) {
		root = insert(rand() % 100, root);
	}
	pre_Node = inorder_root = NULL;
	pre_Node = NULL; 
	__build_inorder_thread(root);
	pre_order(root); printf("\n");
	in_order(root); printf("\n");
	post_order(root); printf("\n");

	Node* node = inorder_root;
	while (node) {
		printf("%3d", node->key);
		node = getNext(node);

	}
	printf("\n");
	clear(root);

	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值