//非递归遍历一棵树 需要借助栈
#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 = 1;
root->pLeft = (Tree*)malloc(sizeof(Tree));
root->pLeft->nValue = 2;
root->pRight = (Tree*)malloc(sizeof(Tree));
root->pRight->nValue = 3;
root->pLeft->pLeft = (Tree*)malloc(sizeof(Tree));
root->pLeft->pLeft->nValue = 4;
root->pLeft->pLeft->pLeft = NULL;
root->pLeft->pLeft->pRight = NULL;
root->pLeft->pRight = (Tree*)malloc(sizeof(Tree));
root->pLeft->pRight->nValue = 5;
root->pLeft->pRight->pLeft = NULL;
root->pLeft->pRight->pRight = NULL;
root->pRight->pLeft = (Tree*)malloc(sizeof(Tree));
root->pRight->pLeft->nValue = 6;
root->pRight->pLeft->pLeft = NULL;
root->pRight->pLeft->pRight = NULL;
root->pRight->pRight = (Tree*)malloc(sizeof(Tree));
root->pRight->pRight->nValue = 7;
root->pRight->pRight->pLeft = NULL;
root->pRight->pRight->pRight = NULL;
frontView(root);
middleView(root);
backView(root);
return 0;
}
因为还没有学C++就开始学习了数据结构,所以不想调用系统的栈来实现, 于是乎自己编写push pop函数解决对栈的操作实现对二叉树的遍历
大概的思想参见这篇博文http://www.cnblogs.com/dolphin0520/archive/2011/08/25/2153720.html 原博主的思路非常棒