• 1086. Tree Traversals Again (25)-树的遍历


    题意:用栈的push、pop操作给出一棵二叉树的中序遍历顺序,求这棵二叉树的后序遍历。

    需要一个堆结构s,一个child变量(表示该节点是其父亲节点的左孩子还是右孩子),父亲节点fa
    对于push v操作:
    1).第一个push肯定是根节点root。
    2).根据child变量,建立fa与v的父子关系。
    3).由于是中序遍历,所以接下来的节点必定是v的left(如果有的话),child=left,fa=v;
    4).然后进行push操作

    对于pop操作:
    1).根据中序遍历性质,可知接下来的节点必定是pop节点的右孩子(如果有的话),child=right,fa=s.top()
    2).进行pop操作。

    #include <iostream>
    #include <cstdio>
    #include <algorithm>
    #include <string.h>
    #include <cmath>
    #include <stack>
    #define LEFT 0
    #define RIGHT 1
    using namespace std;
    
    const int maxn=35;
    stack<int> s;
    
    struct Node{
        int left=-1;
        int right=-1;
    }node[maxn];
    
    bool first=true;
    void postOrder(int u){
        if(u==-1)
            return;
        postOrder(node[u].left);
        postOrder(node[u].right);
        if(first){
            first=false;
            printf("%d",u);
        }
        else{
            printf(" %d",u);
        }
    }
    int main()
    {
        int n,v;
        int root=-1,fa;
        int child=LEFT;
        char str[10];
        scanf("%d",&n);
        while(scanf("%s",str)!=EOF){
            //if(str[0]=='y')
            //    break;
            if(strcmp(str,"Push")==0){
                scanf("%d",&v);
                if(root==-1){
                    root=v;
                }
                else{
                    if(child==LEFT){
                        node[fa].left=v;
                    }
                    else{
                        node[fa].right=v;
                    }
                }
                fa=v;
                child=LEFT;
                s.push(v);
            }
            else{
                child=RIGHT;
                fa=s.top();
                s.pop();
            }
        }
        postOrder(root);
        return 0;
    }
    View Code
  • 相关阅读:
    easyui datagrid 前后台代码
    JVM
    序列化
    Android UI设计
    多线程
    泛型
    字符串
    B+树:MySql数据库索引是如何实现的
    大数据判存算法:海量数据中快速判断某个数据是否存在
    陌生单词
  • 原文地址:https://www.cnblogs.com/chenxiwenruo/p/6388909.html
Copyright © 2020-2023  润新知