首页 > 代码库 > 非递归的方法遍历二叉树

非递归的方法遍历二叉树

//非递归遍历一棵树 需要借助栈

#include<stdio.h>
#include<stdlib.h>

struct Tree
{
  int nValue;
  Tree *pLeft;
  Tree *pRight;
};

struct Stack
{
  Tree *root;
  Stack *pNext;
};

Stack *pStack = NULL;

void push(Tree *root)
{
  Stack *temp = (Stack*)malloc(sizeof(Stack));
  temp->root = root;
  temp->pNext = pStack;
  pStack = temp;
}

void pop()
{
  if(pStack == NULL)
    {
      return;
    }

    Stack *del = pStack;
    pStack = pStack->pNext;
    free(del);
    del = NULL;
}

Tree *root = NULL;

//前序遍历一棵树

void frontView(Tree *root)
{
  while(root!=NULL || pStack!= NULL)
    {
      while(root != NULL)
	{
	  printf("%d ",root->nValue);
	  push(root);
	  root = root->pLeft;
	}
      if(pStack != NULL)
	{
	  root = pStack->root;
	  pop();
	  root = root->pRight;
	}
    }
  printf("\n");
}

//中序遍历
void middleView(Tree *root)
{
  while(root != NULL || pStack != NULL)
    {
      while(root != NULL)
	{
	  push(root);
	  root = root->pLeft;
	}
      if(pStack != NULL)
	{
	  root = pStack->root;
	  printf("%d ",root->nValue);
	  pop();
	  root = root->pRight;
	}
    }
  printf("\n");
}

//后序遍历
void backView(Tree* root)
{
  Tree* current = NULL;
  Tree* previous = NULL;
  push(root);
  while(pStack != NULL)
    {
      current = pStack->root;
      if(current->pLeft == NULL && current->pRight == NULL ||
	 (previous != NULL && 
	  (previous == current->pLeft || previous == current->pRight)))
	{
	  printf("%d ",current->nValue);
	  pop();
	  previous = current;
	}
      else
	{
	  if(current->pRight != NULL)
	    {
	      push(current->pRight);
	    }
	  if(current->pLeft != NULL)
	    {
	      push(current->pLeft);
	    }
	}
    }
  printf("\n");
}

int main()
{
  //用世界上最nb的算法生成一棵满二叉树...
  root = (Tree*)malloc(sizeof(Tree));
  root->nValue = http://www.mamicode.com/1;>
因为还没有学C++就开始学习了数据结构,所以不想调用系统的栈来实现, 于是乎自己编写push pop函数解决对栈的操作实现对二叉树的遍历

大概的思想参见这篇博文http://www.cnblogs.com/dolphin0520/archive/2011/08/25/2153720.html 原博主的思路非常棒