王道数据结构 (11) 树的后序遍历非递归代码实现

代码实现:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define ElementType char
int top_S1 = -1; //定义栈S1 top下标
int top_S2 = -1; //定义栈S2 top下标

// 结点结构体
typedef struct BinTNode
{
  ElementType data;
  struct BinTNode *left;
  struct BinTNode *right;
} BinTNode, *BinTree;

// 初始化树形结构
BinTNode *CreateBiTree(BinTNode *T)
{
  T = (BinTNode *)malloc(sizeof(BinTNode));
  T->data = 'A';
  T->left = (BinTNode *)malloc(sizeof(BinTNode));
  T->left->data = 'B';
  T->right = (BinTNode *)malloc(sizeof(BinTNode));
  T->right->data = 'C';

  T->left->left = (BinTNode *)malloc(sizeof(BinTNode));
  T->left->left->data = 'D';
  T->left->right = (BinTNode *)malloc(sizeof(BinTNode));
  T->left->right->data = 'E';
  T->left->right->left = NULL;
  T->left->right->right = NULL;
  T->left->left->left = (BinTNode *)malloc(sizeof(BinTNode));
  T->left->left->left->data = 'H';
  T->left->left->left->left = NULL;
  T->left->left->left->right = NULL;
  T->left->left->right = (BinTNode *)malloc(sizeof(BinTNode));
  T->left->left->right->data = 'I';
  T->left->left->right->left = NULL;
  T->left->left->right->right = NULL;

  T->right->left = (BinTNode *)malloc(sizeof(BinTNode));
  T->right->left->data = 'F';
  T->right->left->left = NULL;
  T->right->left->right = NULL;
  T->right->right = (BinTNode *)malloc(sizeof(BinTNode));
  T->right->right->data = 'G';
  T->right->right->left = NULL;
  T->right->right->right = NULL;

  return T;
}

// 栈S1 - 进栈push
void push_S1(BinTNode **stack, BinTNode *elem)
{
  stack[++top_S1] = elem;
}

// 栈S2 - 进栈push
void push_S2(BinTNode **stack, BinTNode *elem)
{
  stack[++top_S2] = elem;
}

//栈S1 - 弹栈pop
void pop_S1()
{
  if (top_S1 == -1)
  {
    return;
  }
  top_S1--;
}

//栈S2 - 弹栈pop
void pop_S2()
{
  if (top_S2 == -1)
  {
    return;
  }
  top_S2--;
}

// 遍历过程中,输出结点值
void printElement(BinTNode *elem)
{
  printf("%c ", elem->data);
}

//获取栈顶元素
BinTNode *getTop_S1(BinTNode **stack)
{
  return stack[top_S1];
}

//获取栈顶元素
BinTNode *getTop_S2(BinTNode **stack)
{
  return stack[top_S2];
}

//非递归遍历 - 左右根
void PostOrderTraverse(BinTNode *Tree)
{
  BinTNode *S1[30]; // 辅助栈
  BinTNode *S2[30];
  BinTNode *T = Tree; // 定义临时指针
  BinTNode *Temp;
  push_S1(S1, T); // 初始化S1的top元素是树的根结点
  while (top_S1 != -1)
  {
    T = getTop_S1(S1); // S1的栈顶元素弹出
    pop_S1();          // 栈顶元素弹栈
    push_S2(S2, T);

    if (T->left != NULL || T->right != NULL)
    { // 栈顶元素有孩子结点
      if (T->left != NULL)
        push_S1(S1, T->left);
      if (T->right != NULL)
        push_S1(S1, T->right);
    }
  }
  // 逐个弹出S2的元素
  while (top_S2 != -1)
  {
    printElement(getTop_S2(S2));
    pop_S2();
  }
}

int main()
{
  BinTNode *Tree;
  Tree = CreateBiTree(Tree);
  printf("后序遍历:\t");
  PostOrderTraverse(Tree);
  printf("\n");
  return 0;
}

输出:

 

 

 

转载: https://zhuanlan.zhihu.com/p/136124168

posted @ 2020-07-31 16:48  1点  阅读(470)  评论(0编辑  收藏  举报