1086. Tree Traversals Again (25)

来源:互联网 发布:肛泰和马应龙 知乎 编辑:程序博客网 时间:2024/06/08 18:16

An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stack operations are: push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop(). Then a unique binary tree (shown in Figure 1) can be generated from this sequence of operations. Your task is to give the postorder traversal sequence of this tree.


Figure 1

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (<=30) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to N). Then 2N lines follow, each describes a stack operation in the format: "Push X" where X is the index of the node being pushed onto the stack; or "Pop" meaning to pop one node from the stack.

Output Specification:

For each test case, print the postorder traversal sequence of the corresponding tree in one line. A solution is guaranteed to exist. All the numbers must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:
6Push 1Push 2Push 3PopPopPush 4PopPopPush 5Push 6PopPop
Sample Output:
3 4 2 6 5 1题目意思:中序可以由栈完成。现在给出Push和Pop的操作,求出二叉树的后序。思路:用一个数组记录节点,Pop的记录为0,Push就记录原本值,然后dfs生成树,然后递归生成后序顺序输出。给出N(30)个节点,如果全部是右子树用数组得分配特别的内存。用个map记录。#include <iostream>#include <cstdio>#include <cstring>#include <map>using namespace std;const int maxn = 70;int n, tot;int node[maxn], post[maxn];map<int, int> tree;void dfs(int idx){    if(node[tot] == 0){        ++tot;        return;    }    tree[idx] = node[tot++];    dfs(2 * idx + 1);    dfs(2 * idx + 2);}void postOrder(int idx){    if(tree.count(idx) == 0)        return;    postOrder(2 * idx + 1);    postOrder(2 * idx + 2);    post[tot++] = tree[idx]; }int main(){    scanf("%d", &n);    char str[5];    int key;    for(int i = 0; i < 2 * n; i++){        scanf("%s", str);        if(strcmp(str, "Push") == 0){            scanf("%d", &key);            node[i] = key;        }    }//    for(int i = 0; i < 2 * n; i++)//        printf("%d\n", node[i]);    dfs(0);    tot = 0;    postOrder(0);    for(int i = 0; i < n; i++){        if(i)            printf(" ");        printf("%d", post[i]);    }    return 0;}
0 0
原创粉丝点击