二叉树非递归遍历C语言实现

来源:互联网 发布:淘宝c店的运营方案 编辑:程序博客网 时间:2024/05/17 06:37

二叉树非递归遍历实现——C语言实现

二叉树非递归遍历:前、中、后序三种遍历需要用到栈,层序遍历需要用到队列。首先用c语言实现栈和队列,然后再实现二叉树的非递归遍历

编程环境:Visual Studio 2010

static void Visit(Position P)
{
 printf("%d ", P->Data);
}

void PreOrder(Tree T)//前序遍历
{
 Stack S;
 Position P;

 S = InitStack();//创建栈
 P = T;
 while(P || !StackEmpty(S))//StackEmpty栈是否为空
 {
  if(P)
  {
   Visit(P);
   if(P->Right)
    Push(P->Right, S);
   P = P->Left;
  }
  else
   P = Pop(S);
 }
 DestoryStack(S);//销毁栈
}

void InOrder(Tree T)//中序遍历
{
 Stack S;
 Position P;

 S = InitStack();//创建栈
 P = T;
 while(P || !StackEmpty(S))
 {
  if(P)
  {
   Push(P, S);
   P = P->Left;
  }
  else
  {
   P = Pop(S);
   Visit(P);
   P = P->Right;
  }
 }
 DestoryStack(S);//销毁栈
}

void PostOrder(Tree T)//后序遍历
{
 Position preNode, currNode;
 Stack S;

 S = InitStack();
 preNode = NULL;
 Push(T, S);

 while(!StackEmpty(S))//判断栈是否为空
 {
  currNode = Peek(S);
  if(preNode == NULL || preNode->Left == currNode || preNode->Right == currNode)
  {
   if(currNode->Left)
    Push(currNode->Left, S);
   else if(currNode->Right)
    Push(currNode->Right, S);
  }
  else if(currNode->Left == preNode)
  {
   if(currNode->Right)
    Push(currNode->Right, S);
  }
  else
  {
   Visit(currNode);
   Pop(S);
  }
  preNode = currNode;
 }
 DestoryStack(S);//销毁栈
}

void LevelOrder(Tree T)//层序遍历
{
 Queue Q;
 Position P;

 if(T == NULL)
  return;
 Q = InitQueue();
 Enqueue(T, Q);
 while(!QueueEmpty(Q))//判断队列是否为空
 {
  P = Dequeue(Q);
  Visit(P);
  if(P->Left)
   Enqueue(P->Left, Q);
  if(P->Right)
   Enqueue(P->Right, Q);
 }
 DestoryQueue(Q);//销毁队列
}

原创粉丝点击