递归:
1.先序
void PreOrder(T)
{
if T != NULL
Print T
PreOrder(T.lchild)
PreOrder(T.rchild)
}
2.中序
void InOrder(T)
{
if T != NULL
InOrder(T.lchild)
Print T
InOrder(T.rchild)
}
3.后序
void PostOrder(T)
{
if T != NULL
PostOrder(T.lchild)
PostOrder(T.rchild)
Print T
}
非递归:
1.先序:
void PreOrder(T)
{
t = T
Stack stack
while t != NULL || !stack.empty()
if t != NULL
print t
Push(stack, t)
t = t.lchild
else
t = Pop(stack)
t = t.rchild
}
2.中序
void InOrder(T)
{
t = T
Stack stack
while t != NULL || !stack.empty()
if t != NULL
Push(stack, t)
t = tlchild
else
t = Pop()
print t
t = t.rchild
}
3.后序
后序遍历由于遍历父节点是在遍历子节点之后,而且左节点和右节点遍历后的行为不一样,
因此需要用变量来记录前一次访问的节点,根据前一次节点和现节点的关系确定操作。http://blog.csdn.net/hackbuteer1/article/details/6583988
void PostOrder(T)
{
if T == NULL
return;
Stack stack
Push(stack, T)
while(!stack.empty())
{
cur = s.top()
if (pre == NULL || pre->lchild == cur || pre->rchild == cur)
{
if (cur->lchild != NULL)
Push(stack, cur->lchild)
else if (cur->rchild != NULL)
Push(stack, cur->rchild)
}
else if (cur->lchild == pre)
{
if (cur->rchild != NULL)
Push(stack, cur->rchild)
}
else
{
print cur
s.pop()
}
pre = cur
}
}
不用栈非递归中序遍历(需要父节点)
while(t != null)
{
while(t->left && p != t->left && p != t->right)
{
<span style="white-space:pre"> </span>p = t;
<span style="white-space:pre"> </span>t = t->left;
}
if(p != t->right)
{
<span style="white-space:pre"> </span>print t;
<span style="white-space:pre"> </span>if(t->right)
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span> p = t;
<span style="white-space:pre"> </span> t = t->right;
<span style="white-space:pre"> </span>}
}
else
{
<span style="white-space:pre"> </span>p = t;
<span style="white-space:pre"> </span>t = t->parent;
}
}