二叉树结点结构
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
}
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
}
//中序递归遍历
void ReInOrder(BinaryTreeNode* pRoot)
{
if(pRoot!=NULL)
{
ReInOrder(pRoot->m_pLeft);
cout<<pRoot->m_nValue<<" ";
ReInOrder(pRoot->m_pRight);
}
}
//中序非递归遍历
void NotReInOrder(BinaryTreeNode* pRoot)
{
stack<BinaryTreeNode*> stk;
if(pRoot==NULL)
return NULL;
BinaryTreeNode* p=pRoot;
while(p!=NULL ||!stk.empty())
{
while(p!=NULL)
{
stk.push(p);
p=p->m_pLeft;
}
if(!stk.empty())
{
p=stk.top();
cout<<p->m_nValue<<" ";
stk.pop();
p=p->m_pRight;
}
}
}
//前序递归遍历
void ReInOrder(BinaryTreeNode* pRoot)
{
if(pRoot!=NULL)
{
cout<<pRoot->m_nValue<<" ";
ReInOrder(pRoot->m_pLeft);
ReInOrder(pRoot->m_pRight);
}
}
//前序非递归遍历
void NotRePreOrder(BinaryTreeNode* pRoot)
{
stack<BinaryTreeNode*> stk;
if(pRoot==NULL)
return NULL;
BinaryTreeNode* p=pRoot;
while(p!=NULL ||!stk.empty())
{
while(p!=NULL)
{
cout<<p->m_nValue<<" ";
stk.push(p);
p=p->m_pLeft;
}
if(!stk.empty())
{
p=stk.top();
stk.pop();
p=p->m_pRight;
}
}
}
//后序递归遍历
void ReLastOrder(BinaryTreeNode* pRoot)
{
if(pRoot!=NULL)
{
ReInOrder(pRoot->m_pLeft);
ReInOrder(pRoot->m_pRight);
cout<<pRoot->m_nValue<<" ";
}
}
struct Node
{
BinaryTreeNode* BTNode;
bool isFirst;
}
//后序非递归遍历
void NotReLastOrder(BinaryTreeNode* pRoot)
{
if(pRoot==NULL)
return;
BinaryTreeNode* R=pRoot;
stack<Node*> stk;
while(R!=NULL && !stk.empty())
{
while(R!=NULL)
{
Node* p=(Node *)malloc(sizeof(Node));//添加了bool类型
p->BTNode=R;
p->isFirst=true;
stk.push(p);
R=R->m_pLeft;
}
if(!stk.empty())
{
p=stk.top();
stk.pop();
R=p->BTNode;
if(p.isFirst)//第一次出现在栈顶,重新推入
{
p.isFirst=false;
stk.push(p);
R=R->m_pRight;
}
else
{
cout<<p->BTNode<<" ";//第二次出现在栈顶,直接打印
R=NULL;
}
}
}
}
//层序遍历
void levelTranverse(BinaryTreeNode* pRoot)
{
if(pRoot==NULL)
return;
dequen<BinaryTreeNode*> Q;
BinaryTreeNode* R=pRoot;
Q.push_back(R);
while(!Q.empty())
{
BinaryTreeNode* p=Q.front();
Q.pop_front();
cout<<p->m_nValue<<" ";
if(p->m_pLeft)
Q.push_back(p->m_pLeft);
if(p->m_pRight)
Q.push_back(p->m_pRight);
}
}