线索二叉树

来源:互联网 发布: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
原创粉丝点击