Friday, October 20, 2006

遍历二叉树的非递归算法

typedef int TElemType;
typedef struct BiTNode
{
  TElemType data;
  struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;

// 中序遍历的非递归算法
bool InOrderTraverse(BiTree T, bool (*Visit)(TElemType e))
{
  if (NULL == T) return false;

  Stack S; //辅助的栈
  BiTree p = T;

  InitStack(S);
  while (p || !StackEmpty(S))
  {
    if (p)
    {
      Push(S, p);
      p = p->lchild;
    }
    else
    {
      Pop(S, p);
      if (!Visit(p->data))
      {
        DestroyStack(S);
        return false;
      }
      p = p->rchild;
    }
  }
  DestroyStack(S);
  return true;
}

// 层次遍历的非递归算法
bool HierarchyTraverse(BiTree T, bool (*Visit)(TElemType e))
{
  if (NULL == T) return false;

  LinkQueue *Q; //辅助的队列
  BiTree p = T;

  InitQueue(Q);
  Visit(p->data);
  if (p->lchild) EnQueue(Q, p->lchild);
  if (p->rchild) EnQueue(Q, p->rchild);
  while (!QueueEmpty(Q))
  {
    DeQueue(Q, p);
    Visit(p->data);
    if (p->lchild) EnQueue(Q, p->lchild);
    if (p->rchild) EnQueue(Q, p->rchild);
  }
  DestroyQueue(Q);
  return true;
}

更多见:二叉树非递归遍历算法

No comments: