在学习二叉树的过程中学会的比较易懂的非递归遍历方式:
#include <iostream>
using namespace std;
typedef struct btree
{
int val;
btree* left;
btree* right;
}*pbtree;
pbtree stack[10];
int stacksize = -1;
void printfirst(pbtree tree)
{
pbtree pmove = tree;
while (stacksize != -1 || pmove)
{
while (pmove)
{
cout << pmove->val<<"\t";
stack[++stacksize] = pmove;
pmove = pmove->left;
}
if (stacksize != -1)
{
pmove = stack[stacksize--];
pmove = pmove->right;
}
}
}
void printsecond(pbtree tree)
{
pbtree pmove = tree;
while (pmove || stacksize != -1)
{
while (pmove)
{
stack[++stacksize] = pmove;
pmove = pmove->left;
}
if (stacksize != -1)
{
pmove = stack[stacksize--];
cout << pmove->val<<"\t";
pmove = pmove->right;
}
}
}
void printlast(pbtree tree)
{
pbtree pmove=tree, ppmove = nullptr;
while(pmove)
{
stack[++stacksize] = pmove;
pmove = pmove ->left;
}
while(stacksize!=-1)
{
if (stacksize != -1)
{
pmove = stack[stacksize--];
if (pmove->right == nullptr || pmove->right == ppmove)
{
cout << pmove->val << "\t";
ppmove = pmove;
}
else
{
stack[++stacksize] = pmove;
pmove = pmove->right;
while (pmove)
{
stack[++stacksize] = pmove;
pmove = pmove->left;
}
}
}
}
}
int main()
{
btree tree = { 1,nullptr,nullptr };
btree tree1 = { 2,nullptr,nullptr };
btree tree2 = { 3,nullptr,nullptr };
btree tree3 = { 4,&tree,nullptr };
btree tree4 = { 5,&tree2,&tree1 };
btree tree5 = { 6,&tree4,&tree3 };
printfirst(&tree5);
cout << endl;
printsecond(&tree5);
cout << endl;
printlast(&tree5);
cout << endl;
system("pause");
return 0;
}