创建一个二叉树,并实现对二叉树的中序遍历。
这里用两种方法实现对二叉树的中序遍历:第一种方法:递归方法,该方法不需要使用辅助工具栈;
第二种方法:非递归方法,该方法需要使用栈。
下面是具体实现:
treenode.h
struct BinaryTreenode
{
int mvalue;
BinaryTreenode *pleft;
BinaryTreenode *pright;
};
#include <iostream>
#include <stack>
#include "treenode.h"
using namespace std;
BinaryTreeNode *creatTree(unsigned int n);
void inorder(BinaryTreeNode *proot);
int main()
{
BinaryTreeNode *proot=creatTree(10);
inorder(proot);
return 0;
}
//创建二叉树
BinaryTreeNode *creatTree(unsigned int n)
{
if (n<=0)
{
cout <<"ERROR!" <<endl;
return NULL;
}
BinaryTreeNode *proot=NULL;
BinaryTreeNode *v[20]={NULL};
int i=0,j=0;
int val;
while(i<n)
{
cin >>val;
BinaryTreeNode *pnode=new BinaryTreeNode();
pnode->m_val=val;
pnode->pleft=NULL;
pnode->pright=NULL;
v[i]=pnode;
if (i==0)
{
proot=pnode;
}
else
{
j=(i+1)/2;
if (i&1==1)
{
v[j-1]->pleft=pnode;
}
else
{
v[j-1]->pright=pnode;
}
}
i++;
}
return proot;
}
/*
//递归实现中序遍历
void inorder(BinaryTreeNode *proot)
{
if (proot==NULL)
{
return;
}
if(proot)
{
inorder(proot->pleft);
printf("%d ",proot->m_val);
inorder(proot->pright);
}
}
*/
//非递归实现中序遍历
void inorder(BinaryTreeNode *proot)
{
if (proot==NULL)
{
return;
}
stack<BinaryTreeNode *> st;
while(proot || !st.empty())
{
while(proot)
{
st.push(proot);
proot=proot->pleft;
}
if (st.size()!=0)
{
proot=st.top();
printf("%d ",proot->m_val);
proot=proot->pright;
st.pop();
}
}
}