A clue binary tree that beginners can understand at a glance-data structure clue binary tree

1. Reasons for using clues

The binary linked list is used as a storage structure to find the direct predecessor and direct successor of the node conveniently and quickly . This dynamic access method is to make full use of the empty chain domain in the binary linked list to save the predecessor and successor information of the node in the traversal process.

2. The structure of the clue binary tree node

A binary linked list with n nodes has 2n chain domains; empty chain domains: n+1; non-empty chain domains: n-1 (the line connecting the two points);

Understand the concept of clues

According to different traversal order, it is divided into: pre-order clue binary tree, middle-order clue binary tree, post-order clue binary tree

3. Algorithmic Ideas

  1. In-order threading adopts in-order recursive traversal algorithm framework
  2. Add thread operation is access node operation
  3. Add thread operation needs to use the relationship between the node just visited and the current node, so set a pointer pre to always record the node just visited
    1. If the left subdomain of the current traversal node root is empty, the left subdomain points to pre;
    2. If the right subdomain of the predecessor pre is empty, let the right subdomain point to the current traversal node root;
    3. To prepare for the next time, the current access node root serves as the predecessor of the next access node;

4. Establish a binary tree of middle-order clues

Core algorithm

 5. Complete code

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

typedef struct BiNode
{
	char data;
	int Ltag;
	int Rtag;
	struct BiNode * LChild;
	struct BiNode * RChild;
}BiNode,*BiTree;

BiTree pre;	//全局定义前驱指针

//创建二叉树,按先序遍历输入
void CreateBiTree(BiTree *T)
{
	char ch;
	scanf("%c",&ch);
	if(ch=='#')
        *T=NULL;
	else{
		*T=(BiTree) malloc (sizeof(BiNode));
		(*T)->data=ch;
		CreateBiTree(&(*T)->LChild);
		CreateBiTree(&(*T)->RChild);	
	}
}

//中序线索化
void Inthread (BiTree root)
{
	if (root !=NULL )
	{
		Inthread(root->LChild);//线索化左子树
		printf(" %c ",root->data);
		if (root->LChild==NULL)	//找前驱
		{
			root->Ltag=1;
			root->LChild=pre;	
		}
		if (pre !=NULL && pre->RChild == NULL) //找后继
		{
			pre->RChild=root;
			pre->Rtag=1;
		}
		pre=root;	//让当前结点作为下一次的前驱
		Inthread(root->RChild);//线索化右子树
	}
}

int main()
{
	BiTree T;
	printf("请按照先序遍历的方式输入(为空是输入#): ");
	CreateBiTree(&T);
	printf("中序线索化: ");
	Inthread(T);
	printf("\n");
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_44068262/article/details/106429603