数据结构——使用非递归方法后序遍历二叉树
2017-11-03 15:05
656 查看
使用扩展先序遍历二叉树来进行二叉树的创建,使用非递归方法遍历二叉树,并且不同于书上使用的顺序栈,这里采用链栈,与顺序栈的不同是不能将NULL压栈,因此算法较复杂一些,是一次尝试。
C语言代码:
C语言代码:
#include <stdio.h> #include <malloc.h> #include <stdlib.h> //定义二叉树 typedef struct BinaryTree{ char data; BinaryTree *leftChild; BinaryTree *rightChild; int f; }BinaryTree,*PBinaryTree; //定义一个栈 typedef struct Stack{ PBinaryTree data; Stack *next; }Stack,*PStack; //初始化栈 void initStack(PStack x){ x->data=NULL; x->next=NULL; } //判空 int empty(PStack x){ if(x->next==NULL) return 1; return 0; } //入栈 void push(PStack x,PBinaryTree d){ PStack newNode=(PStack)malloc(sizeof(Stack)); if(!newNode) exit(0); newNode->data=d; newNode->next=x->next; x->next=newNode; } //出栈 PBinaryTree pop(PStack x){ if(empty(x)) return NULL; PBinaryTree pop=x->next->data; PStack popNode=x->next; x->next=popNode->next; free(popNode); return pop; } //释放栈 void delStack(PStack x){ while(!empty(x)) pop(x); free(x); } //扩充的先序遍历二叉树创建树 void createTree(PBinaryTree &root){ char x; scanf("%c",&x); if(x=='.') root=NULL; else{ root=(PBinaryTree)malloc(sizeof(BinaryTree)); if(!root) exit(0); root->data=x; root->f=0; createTree(root 9ff6 ->leftChild); createTree(root->rightChild); } } //后序遍历二叉树 int orderTree(PBinaryTree root){ if(root){ PStack s=(PStack)malloc(sizeof(Stack)); if(!s) exit(0); initStack(s); push(s,root); PBinaryTree p=s->next->data; while(!empty(s)){ while(p->leftChild!=NULL&&p->leftChild->f==0){ push(s,p->leftChild); p=s->next->data; } if(p->rightChild!=NULL&&p->rightChild->f==0){ push(s,p->rightChild); p=s->next->data; } if((p->leftChild==NULL||p->leftChild->f==1)&&(p->rightChild==NULL||p->rightChild->f==1)){ printf("%2c",p->data); p->f=1; pop(s); if(s->next==NULL) p=NULL; else p=s->next->data; } } return 0; } else return 1; } int main(){ PBinaryTree myTree; printf("请按扩展先序遍历创建二叉树:\n"); createTree(myTree); orderTree(myTree); return 0; }
相关文章推荐
- 数据结构 分别用递归和非递归方法实现二叉树先序,中序,后序遍历
- 数据结构——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 数据结构学习笔记(三) 树形结构之二叉树的前、中、后序遍历递归方法
- 数据结构 — 实现二叉树的前序,中序,后序遍历(非递归)
- iOS:二叉树多级表格的使用,使用三方库TreeTableView-master实现对json解析数据的递归遍历整理成树状结构
- 数据结构(一)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- (编程训练)再回首,数据结构——二叉树的前序、中序、后序遍历(递归)
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- (编程训练)再回首,数据结构——二叉树的前序、中序、后序遍历(非递归)
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 【数据结构基础】非递归后序遍历二叉树
- 数据结构——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- C#使用前序遍历、中序遍历和后序遍历打印二叉树的方法
- 数据结构上机测试4.1:二叉树的遍历与应用1【根据二叉树的前序序列和中序序列求后序序列方法1,2】
- 数据结构基础 后序遍历和中序遍历还原二叉树