PAT 03-3. Tree Traversals Again (25)

来源:互联网 发布:2钻淘宝店铺值多少钱 编辑:程序博客网 时间:2024/06/09 14:33


03-3. Tree Traversals Again (25)

题目链接:http://www.patest.cn/contests/mooc-ds/03-3


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

解题报告:看图就可以知道树是怎么建的,每次的结点的父亲都是栈顶的元素,即使遇到的是pop,也是先取栈顶元素作为父亲再弹出。后序遍历输出直接用dfs就可以了。

#include <bits/stdc++.h>using namespace std;const int maxn = 35;struct node {    int left;    int right;    node() {        left = -1, right = -1;    }} tree[31];stack<int> ss;int flag = 0;void dfs(int r) {    if(tree[r].left != -1) {        dfs(tree[r].left);    }    if(tree[r].right != -1) {        dfs(tree[r].right);    }    if(flag == 0) {        printf("%d", r);        flag = 1;    } else {        printf(" %d", r);    }}int main() {    int n, root, top, value;    char s[6];    cin >> n;    cin >> s >> root;   //第一个是root    top = root;    ss.push(root);    while (n) {        cin >> s;        if(s[1] == 'u') {            cin >> value;            if(tree[top].left == -1) {                tree[top].left = value;            } else {                tree[top].right = value;            }            top = value;            ss.push(value);        } else {            top = ss.top();            ss.pop();            n --;        }    }    dfs(root);    printf("\n");    return 0;}



0 0
原创粉丝点击