//好久不用C++许多语法细节都忘记了...费了九牛二虎之力还搞的那么复杂,Anyway,下午把前序遍历给写出来了,还是有点成绩的。。。
#include<iostream>
#include<stack>
using namespace std;
typedef int dataType;
typedef struct BiTree
{
dataType data;
BiTree *lchild;
BiTree *rchild;
}BiTree,*treePoint;
treePoint CreateTree(treePoint root)
{
dataType data;
cin>>data;
if(data==-1)
{
return NULL;
}
root=new BiTree;
root->data=data;
root->lchild=CreateTree(root->lchild);
root->rchild=CreateTree(root->rchild);
return root;
}
void PreOrderTraverse(treePoint root)
{
if(root==NULL)
cout<<"hello world!"<<endl;
BiTree *bt=NULL;
if(root==NULL)
return;
cout<<root->data<<endl;
stack<BiTree *>st;
st.push(root);
while(!st.empty())
{
bt=st.top();
while(bt->lchild!=NULL)
{
st.push(bt->lchild);
cout<<bt->lchild->data<<endl;
bt=bt->lchild;
}
//st.pop();
bt=st.top();
st.pop();
if(bt->rchild!=NULL)
{
st.push(bt->rchild);
cout<<bt->rchild->data<<endl;
continue;
}else
{
while(!st.empty())
{
bt=st.top();
st.pop();
if(bt->rchild!=NULL)
{
st.push(bt->rchild);
cout<<bt->rchild->data<<endl;
break;
}
}
}
}
}
int main()
{
treePoint root=NULL;
root=CreateTree(root);
PreOrderTraverse(root);
system("pause");
return 0;
}原文地址:http://blog.csdn.net/mnmlist/article/details/42526817