二叉树的遍历:
#include<iostream>
#include<vector>
#include<stack>
#include<assert.h>
using namespace std;
//前序遍历打印二叉树:
void PreOrder(BtNode *p)
{
if(NULL != p)
{
cout<<p->data<<" ";
PreOrder(p->leftchild);
PreOrder(p->rightchild);
}
}
//中序遍历打印二叉树:
void InOrder(BtNode *p)
{
if(NULL != p)
{
InOrder(p->leftchild);
cout<<p->data<<" ";
InOrder(p->rightchild);
}
}
//后序遍历打印二叉树:
void PastOrder(BtNode *p)
{
if(NULL != p)
{
PastOrder(p->leftchild);
PastOrder(p->rightchild);
cout<<p->data<<" ";
}
}
//非递归前序遍历打印二叉树:
void NicePreOrder(BtNode *p)
{
if(p == NULL) return ;
stack<BtNode *> st;
st.push(p);
while(!st.empty())
{
BtNode * str = st.top();
st.pop();
cout<<str->data<<" ";
if(str ->rightchild !=NULL)
{
st.push(str->rightchild);
}
if(str->leftchild != NULL)
{
st.push(str->leftchild);
}
}
cout<< endl;
}
//非递归中序遍历打印二叉树:
void NiceInOrder(BtNode *ptr)
{
if(NULL == ptr) return ;
stack<BtNode*> st;
while(ptr != NULL || !st.empty())
{
while(ptr != NULL)
{
st.push(ptr);
ptr = ptr->leftchild;
}
ptr = st.top(); st.pop();
cout<<ptr->data<<" ";
ptr = ptr->rightchild;
}
cout<<endl;
}
//非递归后序遍历打印二叉树:
void NicePastOrder(BtNode *ptr)
{
if(NULL == ptr) return ;
stack<BtNode*> st;
BtNode *tag = NULL; //tag用来保存结点是否已被访问过
while(ptr != NULL || !st.empty())
{
while(ptr != NULL)
{
st.push(ptr);
ptr = ptr->leftchild;
}
ptr = st.top(); st.pop();if(ptr->rightchild == NULL ||ptr->rightchild == tag)
{
cout<<ptr->data<<" ";
tag = ptr;
ptr = NULL;
}
else
{
st.push(ptr);
ptr = ptr->rightchild;
}
}
cout<<endl;
}
二叉树_二叉树的遍历
最新推荐文章于 2022-04-28 11:31:29 发布