1. 程式人生 > 其它 >二叉樹的中序線索化及遍歷

二叉樹的中序線索化及遍歷

技術標籤:資料結構與演算法二叉樹visual studio code

二叉樹的中序線索化及遍歷


先序建立線索二叉樹。
線索二叉樹的中序線索化。
帶頭節點的線索二叉樹的中序線索化。
線索二叉樹的中序遍歷。

直接上程式碼,寒假完善先序線索化、後序線索化和相關圖解。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
using namespace std;

typedef char DataType;

typedef enum
PointerTag { Link, Thread }; typedef struct node { DataType data; struct node *lchild; struct node *rchild; PointerTag LTag; PointerTag RTag; }BiThrNode, *BiThrTree; //先序建立線索二叉樹 void CreateBiThrTree(BiThrTree *root) { char c; cin >> c; if (c == '#') *root=
NULL; else { (*root) = (BiThrTree)malloc(sizeof(BiThrNode)); (*root)->data = c; (*root)->LTag = Link; (*root)->RTag = Link; CreateBiThrTree(&(*root)->lchild); CreateBiThrTree(&(*root)->rchild); } } //二叉樹的中序線索化 void InThreading
(BiThrTree root, BiThrTree *pre) { if (root == NULL) return; InThreading(root->lchild, pre); if (root->lchild == NULL) { root->LTag = Thread; root->lchild = *pre; } if ((*pre)->rchild == NULL) { (*pre)->RTag = Thread; (*pre)->rchild = root; } *pre = root; InThreading(root->rchild, pre); } //增加頭結點的中序線索化 void InOrderThreading(BiThrTree *root, BiThrTree T) { *root = (BiThrTree)malloc(sizeof(BiThrNode)); (*root)->LTag = Link; (*root)->RTag = Thread; (*root)->rchild = (*root); if (T == NULL) { (*root)->lchild = (*root); } BiThrTree pre; pre = (*root); (*root)->lchild = T; InThreading(T, &pre); pre->rchild = *root; pre->RTag = Thread; (*root)->rchild = pre; } //非遞迴遍歷線索二叉樹 void InOrderTraverse(BiThrTree T) { BiThrNode *p = T->lchild; while (p != T) { while (p->LTag == Link) p = p->lchild; cout << p->data << " "; while (p->RTag == Thread && p->rchild != T) { p = p->rchild; cout << p->data << " "; } p = p->rchild; } cout << endl; } //測試序列:ABD##E##CF### int main() { BiThrTree root, T; CreateBiThrTree(&root); InOrderThreading(&T, root); cout << "中序遍歷二叉樹的結果為:"; InOrderTraverse(T); system("pause"); return 0; }