标签:c
先序遍历:
void preOrder(Node *p) //非递归 { if(!p) return; stack<Node*> s; Node *t; s.push(p); while(!s.empty()) { t=s.top(); printf("%d\n",t->data); s.pop(); if(t->right) s.push(t->right); if(t->left) s.push(t->left); } }
中序遍历:
void
inOrder(Node *p)
{
if
(!p)
return
;
stack< pair<Node*,
int
> > s;
Node *t;
int
unUsed;
s.push(make_pair(p,1));
while
(!s.empty())
{
t=s.top().first;
unUsed = s.top().second;
s.pop();
if
(unUsed)
{
if
(t->right)
s.push( make_pair(t->right,1) );
s.push( make_pair(t,0) );
if
(t->left)
s.push( make_pair(t->left,1));
}
else
printf
(
"%d\n"
,t->data);
}
}
void postOrder(Node *p) { if(!p) return; stack<pair<Node*,int> > s; Node *t; int unUsed; s.push(make_pair(p,1)); while(!s.empty()) { t=s.top().first; unUsed=s.top().second; s.pop(); if(unUsed) { s.push(make_pair(t,0); if(t->right) s.push(make_pair(t->right,1)); if(t->left) s.push(make_pair(t->left,1)); } else printf("%d\n",t->data);
标签:c
原文地址:http://blog.csdn.net/yusiguyuan/article/details/39295831