非递归算法将空间消耗从栈区转换到堆区,避免了栈溢出的导致程序崩溃。
typedef struct trnode
{
char x;
struct trnode* lchild, * rchild;
} Trnode, *Tree;
Tree buildtree(char * &s)
{
if(*s && *s != ',')
{
Tree tr = (Tree) malloc( sizeof(Trnode) );
tr->x = *s;
tr->lchild = buildtree(++s);
tr->rchild = buildtree(++s);
return tr;
}
return NULL;
}
void inorder(Tree rt) //中序
{
stack<Tree> S;
S.push(rt);
Tree p = rt;
while(!S.empty())
{
while(p)
{
p=p->lchild;
S.push(p);
}
S.pop();
if(S.empty()) break;
p = S.top();
S.pop();
cout<<p->x;
p = p->rchild;
S.push(p);
}
cout<<endl;
}
void preorder(Tree rt) //先序
{
stack<Tree> S;
S.push(rt);
Tree p = rt;
while(!S.empty())
{
while(p)
{
cout<<p->x;
p=p->lchild;
S.push(p);
}
S.pop();
if(S.empty()) break;
p = S.top();
S.pop();
p = p->rchild;
S.push(p);
}
cout<<endl;
}
void postorder(Tree rt) //后序
{
stack<Tree> S;
stack<Tree> ans;
S.push(rt);
Tree p = rt;
while(!S.empty())
{
while(p)
{
ans.push(p);
p=p->rchild;
S.push(p);
}
S.pop();
if(S.empty()) break;
p = S.top();
S.pop();
p = p->lchild;
S.push(p);
}
while( !ans.empty() )
{
cout<<ans.top()->x;
ans.pop();
}
cout<<endl;
}