线索二叉树
来源:互联网 发布:js array 添加数据 编辑:程序博客网 时间:2024/06/05 14:07
利用线索二叉树实现中序遍历
#include <stdio.h>#include <stdlib.h>#include <iostream>using namespace std;//构建线索化二叉树,用其进行中序遍历及中序逆遍历typedef char elemType;typedef enum thread{LINK=1,THLINK}THREAD;typedef struct _node{_node *leftChild;THREAD Lflg;elemType data;_node *rightChild;THREAD Rflag;}ThBiNode;ThBiNode *buyNode(){ThBiNode *tmp = (ThBiNode *)malloc(sizeof(ThBiNode));if (tmp == NULL) exit(-1);memset(tmp, 0, sizeof(ThBiNode));return tmp;}ThBiNode *createThBiTree(char *&str){if (str == NULL || *str == '#') return NULL;ThBiNode *tmp = buyNode();tmp->data = *str;if ((tmp->leftChild=createThBiTree(++str)) != NULL) {tmp->Lflg=LINK;}if ((tmp->rightChild = createThBiTree(++str)) != NULL) {tmp->Rflag=LINK;}return tmp; }void createInOrder(ThBiNode* p, ThBiNode* &ptr){if (p == NULL) return ;createInOrder(p->leftChild,ptr);if (p->Lflg!=LINK){p->leftChild = ptr;p->Lflg = THLINK;}if (ptr!=NULL && ptr->Rflag!=LINK){ptr->rightChild = p;ptr->Rflag = THLINK;}ptr=p;createInOrder(p->rightChild, ptr);}void ThBiTreeInOrder(ThBiNode *p){if (p == NULL)return ;ThBiNode *ptr = NULL;createInOrder(p , ptr);//传递的是ptr的引用ptr->Rflag = THLINK;ptr->rightChild = NULL;}ThBiNode *first(ThBiNode *p){if (p != NULL){while (p->Lflg == LINK){p = p->leftChild;}}return p;}ThBiNode *nextNode(ThBiNode *p){if (p->Rflag == THLINK){return p->rightChild;}return first(p->rightChild);}void inOrder(ThBiNode *ptr)//中序遍历{for (ThBiNode *i= first(ptr); i!=NULL; i=nextNode(i)){cout<<i->data;}}ThBiNode *last(ThBiNode *p){if (p != NULL){while(p->Rflag == LINK){p = p->rightChild;}}return p;}ThBiNode *nextForRe(ThBiNode *p){if (p->Lflg == THLINK){return p->leftChild;}return last(p->leftChild);}void inOrderRes(ThBiNode *ptr){for (ThBiNode *i =last(ptr); i != NULL; i=nextForRe(i)){cout<<i->data;}}int main(){char *str = "ABC##DE##F##G#H##";//先根ThBiNode *root = createThBiTree(str);ThBiTreeInOrder(root);inOrder(root);cout<<endl;inOrderRes(root);}
0 0
- 线索二叉树 --->树
- 线索二叉树算法
- C#线索二叉树
- 线索二叉树
- C#线索二叉树
- 线索二叉树
- 线索二叉树
- 线索化二叉树
- 线索二叉树
- C#线索二叉树
- C#线索二叉树
- 线索二叉树
- 线索二叉树实例
- 线索二叉树
- 线索二叉树算法
- C++线索二叉树
- 线索二叉树
- 线索二叉树实现
- 判断二叉树是否对称
- 逆序输出正整数
- 003-102-Binary Tree Level Order Traversal 层序遍历二叉树
- 一次循环查找字符串中第一个不重复的字节
- 计算机网络复习(第一章 概述)
- 线索二叉树
- webApp,在androidstudio上离线打包问题
- Eclipse如何快速修改工程名及包名
- steghide中文演示教程
- POJ 3254 Corn Fields 状压dp
- 背景分割
- webservice入门(一)
- NFV
- C++回顾之C与C++区别_00