二叉树的非递归遍历在面试的时候也会问到,好像后续的非递归遍历比较麻烦,我没有进一步了解,只实现了前序和中序的非递归遍历。
前序:根节点,左孩子,右孩子;
中序:左孩子,根节点,右孩子;
后序:左孩子,右孩子,根节点;
#include <iostream>
#include <stack>
#include <iostream>
using namespace std;
struct BinaryTree
{
int data;
BinaryTree* left;
BinaryTree *right;
};
//中序方式递归遍历二叉树
void InOrder(BinaryTree *root)
{
if (root!=NULL)
{
InOrder(root->left);
cout<<root->data<<" ";
InOrder(root->right);
}
//cout<<endl;
}
//中序方式非递归遍历二叉树
void IterInOrderBinaryTree(BinaryTree *root)
{
BinaryTree *p=root;
stack<BinaryTree *> S;
while(p||!S.empty())
{
while(p)
{
S.push(p);
p=p->left;
}
if (!S.empty())
{
p=S.top();
S.pop();
cout<<p->data<<" ";
p=p->right;
}
}
cout<<endl;
}
//前序遍历二叉树,递归
void Pre(BinaryTree *root)
{
if (root!=NULL)
{
cout<<root->data<<" ";
Pre(root->left);
Pre(root->right);
}
//cout<<endl;
}
//前序1遍历二叉树,非递归
void PreIter(BinaryTree *root)
{
stack<BinaryTree *>S;
BinaryTree *p=root;
while(p||!S.empty())
{
while(p!=NULL)
{
cout<<p->data<<" ";
S.push(p);
p=p->left;
}
if (!S.empty())
{
p=S.top();
S.pop();
p=p->right;
}
}
cout<<endl;
}
//以先序方式构造二叉树
void ConstructBinaryTree(BinaryTree **root)
{
int n;
cin>>n;
if (n<0)
{
*root=NULL;
}
else
{
*root=(BinaryTree*)malloc(sizeof(BinaryTree));
(*root)->data=n;
ConstructBinaryTree(&(*root)->left);
ConstructBinaryTree(&(*root)->right);
}
}
int main()
{
BinaryTree *root=NULL;
ConstructBinaryTree(&root);
cout<<"递归前序遍历:";
Pre(root);
cout<<endl;
cout<<"非递归前序遍历:";
PreIter(root);
cout<<"递归中序遍历:";
InOrder(root);
cout<<endl;
cout<<"非递归中序遍历:";
IterInOrderBinaryTree(root);
return 0;
}