zoukankan      html  css  js  c++  java
  • 6_38_二叉树的后序遍历非递归算法(和先序有些许不一样)

    #include<stdio.h>
    #include<stdlib.h>
    #include<malloc.h>
    typedef struct node
    {
        int data,tag;
        struct node*lchild,*rchild;
    }tnode,*tree;
    tree creat()
    {
        int x;
        tree t;
        scanf("%d",&x);
        if(x==0)t=NULL;
        else
        {
            t=(tnode*)malloc(sizeof(tnode));
            t->data=x;
            t->lchild=creat();
            t->rchild=creat();
        }
        return t;
    }
    void postorder(tree t)
    {
        tree stack[200];
        int top=0;
        while(top||t)
        {
            if(t)
            {
                t->tag=0;//标记未访问结束
                stack[top++]=t;//入栈保存
                t=t->lchild;//进入左子树
            }
            else if(!stack[top-1]->tag)//如果没有访问栈顶的右子树
            {
                t=stack[top-1];//获得栈顶的节点
                t->tag=1;//标记栈顶的节点访问了右节点
                t=t->rchild;//进入栈顶的右节点
            }
            else
               {
                   t=stack[--top];//栈顶元素出栈
                   printf("%d
    ",t->data);//访问完子节点,访问本节点
                   t=NULL;//该节点结束
               }
        }
    }
    void Postorder(tree t)
    {
        tree Stack[200];
        int  TagStack[200],top=0;
        while(t||top)
        {
            if(t)
            {
                Stack[top]=t;
                TagStack[top++]=0;
                t=t->lchild;
            }
            else if(!TagStack[top-1])
            {
                t=Stack[top-1];
                TagStack[top-1]=1;
                t=t->rchild;
            }
            else
            {
                t=Stack[--top];
                printf("%d
    ",t->data);
                t=NULL;
            }
        }
    }
    int main()
    {
        tree t=creat();
        Postorder(t);
    }
    

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    Vim配置及使用技巧
    终端提示符的配置
    Archlinux下i3wm与urxvt的配置
    Linux压缩命令
    Archlinux无线联网教程
    Archlinux安装和使用技巧
    Linux下硬盘分区
    Linux挂载
    Android中pullToRefresh使用
    SVN服务器搭建和使用教程
  • 原文地址:https://www.cnblogs.com/Thereisnospon/p/4768476.html
Copyright © 2011-2022 走看看