数据结构与算法(6-4)线索二叉树
生活随笔
收集整理的這篇文章主要介紹了
数据结构与算法(6-4)线索二叉树
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
優(yōu)勢:便于在中序遍歷下,查找前驅(qū)和后繼。
前驅(qū)/后繼含義:AB中,A是B前驅(qū),B是A后繼。
ltag=0時:lchild指向左孩子? ? ? ? ? ? ? ? ltag=1時:lchild指向前驅(qū)
rtag=0時:rchild指向右孩子? ? ? ? ? ? ? ? rtag=1時:rchild指向后繼
?過程:
1、先前序遍歷創(chuàng)建二叉樹
2、線索化二叉樹
3、線索二叉樹中序遍歷輸出
總代碼:
//線索二叉樹
//優(yōu)勢:便于在中序遍歷下,查找前驅(qū)和后繼
#include<stdio.h>
#include<malloc.h>
#include<string>int index = 0;
int first = 1;
char str[30];
typedef enum { Link, Thread } PointerTag; //0:Link(指向結(jié)點) 1:Thread(指向線索)typedef struct BiThTree
{char data;struct BiThTree* lchild, * rchild; //左孩子、右孩子PointerTag ltag, rtag; //0:指向左/右孩子; 1:指向前驅(qū)/后繼struct BiThTree* parent; //指向雙親結(jié)點
}BiThTree;
BiThTree* head; //頭
BiThTree* Pre; //前一個結(jié)點void Init_BiThTree()
{head = (BiThTree*)malloc(sizeof(BiThTree));head->parent = head;
}//前序遍歷創(chuàng)建二叉樹
void Create_BiThTree(BiThTree* T)
{if (str[index] == '#') //空{(diào)T->data = str[index++];return;}T->parent = Pre; //保存前一個結(jié)點T->data = str[index++];T->lchild = (BiThTree*)malloc(sizeof(BiThTree));T->rchild = (BiThTree*)malloc(sizeof(BiThTree));T->ltag = Link;T->rtag = Link;Pre = T; //保存前一個結(jié)點Create_BiThTree(T->lchild);Create_BiThTree(T->rchild);
}//線索化二叉樹(中序)
void InThreading(BiThTree* T)
{//如果存在if (T->data != '#'){InThreading(T->lchild); //遞歸左子樹//線索化左if (T->lchild->data == '#') //lchild為空,lchild指向前驅(qū){T->ltag = Thread; //線索模式if (first) //首個賦空{(diào)T->lchild->data = '#';first = 0;}elseT->lchild = Pre; //lchild指向前驅(qū)}//線索化右else if (Pre->rchild->data == '#') //前驅(qū)的rchild為空,前驅(qū)的rchild指向后繼{Pre->rtag = Thread; //線索模式Pre->rchild = T; //rchild指向后繼}Pre = T;InThreading(T->rchild); //遞歸右子樹}
}//線索二叉樹中序遍歷
void InOrderThTraverse(BiThTree* T)
{if (T->data != '#'){if (T->ltag == Link)InOrderThTraverse(T->lchild);printf("%c結(jié)點 \tlchild:%c\trchild:%c\n", T->data, T->lchild->data, T->rchild->data);if (T->rtag == Link)InOrderThTraverse(T->rchild);}
}int main()
{printf("請按照前序遍歷順序輸入需要創(chuàng)建的二叉樹結(jié)點:\n");scanf_s("%s", str, 20);Init_BiThTree(); //初始化Create_BiThTree(head); //前序遍歷創(chuàng)建二叉樹Pre = head;InThreading(head); //中序線索化二叉樹InOrderThTraverse(head); //線索二叉樹中序遍歷
}
總結(jié)
以上是生活随笔為你收集整理的数据结构与算法(6-4)线索二叉树的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据结构与算法(6-2)二叉树的存储结构
- 下一篇: 数据结构与算法(6-5)二叉树的应用--