递归
前序遍历
void PreOrder(BtNode *p)
{
if(p != NULL)
{
cout<<p->data<<" ";
PreOrder(p->leftchild);
PreOrder(p->rightchild);
}
}
中序遍历
void InOrder(BtNode *p)
{
if(p != NULL)
{
InOrder(p->leftchild);
cout<<p->data<<" ";
InOrder(p->rightchild);
}
}
后序遍历
void PastOrder(BtNode *p)
{
if(p != NULL)
{
PastOrder(p->leftchild);
PastOrder(p->rightchild);
cout<<p->data<<" ";
}
}
非递归
前序遍历
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 NicePreOrder(BtNode *ptr)
{
if(NULL == ptr) return ;
stack<BtNode*> st;
st.push(ptr);
while(!st.empty())
{
ptr = st.top(); st.pop();
cout<<ptr->data<<" ";
if(ptr->rightchild != NULL)
{
st.push(ptr->rightchild);
}
if(ptr->leftchild != NULL)
{
st.push(ptr->leftchild);
}
}
cout<<endl;
}
后序遍历
void NicePastOrder(BtNode *ptr)
{
if(NULL == ptr) return;
stack<BtNode *> st;
BtNode *tag = NULL;
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;
}