首页 > 代码库 > 非递归的方法遍历二叉树
非递归的方法遍历二叉树
//非递归遍历一棵树 需要借助栈 #include<stdio.h> #include<stdlib.h> struct Tree { int nValue; Tree *pLeft; Tree *pRight; }; struct Stack { Tree *root; Stack *pNext; }; Stack *pStack = NULL; void push(Tree *root) { Stack *temp = (Stack*)malloc(sizeof(Stack)); temp->root = root; temp->pNext = pStack; pStack = temp; } void pop() { if(pStack == NULL) { return; } Stack *del = pStack; pStack = pStack->pNext; free(del); del = NULL; } Tree *root = NULL; //前序遍历一棵树 void frontView(Tree *root) { while(root!=NULL || pStack!= NULL) { while(root != NULL) { printf("%d ",root->nValue); push(root); root = root->pLeft; } if(pStack != NULL) { root = pStack->root; pop(); root = root->pRight; } } printf("\n"); } //中序遍历 void middleView(Tree *root) { while(root != NULL || pStack != NULL) { while(root != NULL) { push(root); root = root->pLeft; } if(pStack != NULL) { root = pStack->root; printf("%d ",root->nValue); pop(); root = root->pRight; } } printf("\n"); } //后序遍历 void backView(Tree* root) { Tree* current = NULL; Tree* previous = NULL; push(root); while(pStack != NULL) { current = pStack->root; if(current->pLeft == NULL && current->pRight == NULL || (previous != NULL && (previous == current->pLeft || previous == current->pRight))) { printf("%d ",current->nValue); pop(); previous = current; } else { if(current->pRight != NULL) { push(current->pRight); } if(current->pLeft != NULL) { push(current->pLeft); } } } printf("\n"); } int main() { //用世界上最nb的算法生成一棵满二叉树... root = (Tree*)malloc(sizeof(Tree)); root->nValue = http://www.mamicode.com/1;>
因为还没有学C++就开始学习了数据结构,所以不想调用系统的栈来实现, 于是乎自己编写push pop函数解决对栈的操作实现对二叉树的遍历大概的思想参见这篇博文http://www.cnblogs.com/dolphin0520/archive/2011/08/25/2153720.html 原博主的思路非常棒
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。