zoukankan      html  css  js  c++  java
  • 6_39_二叉树增加两个域不用栈进行递推后序遍历树

    #include<stdio.h>
    #include<stdlib.h>
    #include<malloc.h>
    typedef struct node
    {
        int data;
        int mark;
        struct node*lchild,*rchild,*parent;
    }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->mark=0;
            t->parent=NULL;//初始化它没有双亲
            t->lchild=creat();//左孩子的双亲是它
                if(t->lchild)t->lchild->parent=t;
            t->rchild=creat();//右孩子的双亲是它
                if(t->rchild)t->rchild->parent=t;
        }
        return t;
    }
    void preorder(tree t)
    {
        if(t)
        {
            printf("tree:%d\t",t->data);
            preorder(t->lchild);
            preorder(t->rchild);
        }
    }
    void postorder(tree t)
    {
        while(t)
        {
            if(t->mark==0){//标志为往左子树走
                t->mark=1;//更改标记为往右
                if(t->lchild)t=t->lchild;//如果左子树存在往左走
            }
            else if(t->mark==1){//往右走
                t->mark=2;
                if(t->rchild)t=t->rchild;
            }
            else if(t->mark==2){//访问本节点
                printf("%d\n",t->data);
                t->mark=0;//把它重置,以便下一次遍历
                t=t->parent;//回到双亲
            }
        }
    }
    int main()
    {
        tree t=creat();
        postorder(t);
        postorder(t);
    }
    

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

  • 相关阅读:
    周志华 机器学习
    王亮 中国科学院自动化研究所
    殷明 合肥工业大学
    批处理命令行 for循环
    CalFrechetDist
    等高线简化线方法对比(多尺度评价方法)
    周成虎
    MFC 使用控制台打印程序信息
    C++ 获得本地磁盘盘符的容量信息
    VS2012+CUDA6.0配置方法
  • 原文地址:https://www.cnblogs.com/Thereisnospon/p/4768474.html
Copyright © 2011-2022 走看看