二叉树的三种遍历的递归和非递归实现,代码如下:
#include <iostream>
#include <deque>
#include <stack>
#include <vector>
using namespace std;
//二叉树定义
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode*m_pRight;
};
//前序遍历,递归
void PreOrderRecur(BinaryTreeNode*pRoot,vector<int>& vecSeq){
if (pRoot==NULL)
{
return;
}
cout << pRoot->m_nValue<<" ";
vecSeq.push_back(pRoot->m_nValue);
PreOrderRecur(pRoot->m_pLeft,vecSeq);
PreOrderRecur(pRoot->m_pRight,vecSeq);
}
//前序遍历,非递归
void PreOrderUnRecur(BinaryTreeNode*head){
if (head==NULL)
{
return;
}
//栈
stack<BinaryTreeNode*> stackTemp;
stackTemp.push(head);
while (!stackTemp.empty())
{
BinaryTreeNode* temp = stackTemp.top();
cout << temp->m_nValue;
stackTemp.pop();
if (temp->m_pRight!=NULL)
{
stackTemp.push(temp->m_pRight);
}
if (temp->m_pLeft!=NULL)
{
stackTemp.push(temp->m_pLeft);
}
}
}
//中序遍历,递归
void InOrderRecur(BinaryTreeNode*tree){
if (tree==NULL)
{
return;
}
InOrderRecur(tree->m_pLeft);
cout << tree->m_nValue;
InOrderRecur(tree->m_pRight);
}
//中序遍历,非递归
void InOrderUnRecur(BinaryTreeNode*head){
if (head==NULL)
{
return;
}
stack<BinaryTreeNode*> stackTemp;
while (!stackTemp.empty()||head!=NULL)
{
if (head!=NULL)
{
stackTemp.push(head);
head = head->m_pLeft;
}
else{
BinaryTreeNode*temp = stackTemp.top();
cout << temp->m_nValue;
stackTemp.pop();
head = head->m_pRight;
}
}
}
//后序遍历,递归
void PostOrderRecur(BinaryTreeNode*tree){
if (tree==NULL)
{
return;
}
PostOrderRecur(tree->m_pLeft);
PostOrderRecur(tree->m_pRight);
cout << tree->m_nValue;
}
//后序遍历,非递归
void PostOrderUnRecur(BinaryTreeNode*pHead){
if (pHead==NULL)
{
return;
}
stack<BinaryTreeNode*> stack1;
stack<BinaryTreeNode*> stack2;
stack1.push(pHead);
while (!stack1.empty())
{
BinaryTreeNode*pTemp = stack1.top();
stack2.push(pTemp);
stack1.pop();
if (pTemp->m_pLeft!=NULL)
{
stack1.push(pTemp->m_pLeft);
}
if (pTemp->m_pRight!=NULL)
{
stack1.push(pTemp->m_pRight);
}
}
while (!stack2.empty())
{
cout << stack2.top()<<" ";
stack2.pop();
}
cout << endl;
}
int main(){
return 0;
}