Tree Traversals Again

来源:互联网 发布:腹部减脂 知乎 编辑:程序博客网 时间:2024/04/29 19:58

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 NN (\le 3030) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to NN). Then 2N2N 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

中序遍历非递归的实现是使用堆栈   所以我们知道出栈的方式就是中序遍历的结果   但是还有一点容易遗漏那就是 进栈的顺序是 先序遍历

1.我们可以根据input 知道  先序遍历 和中序的结果

2.根据先序和中序 我们可以还原二叉树

3.再根据二叉树 后序遍历

#include <stdio.h>#include <stdlib.h>#include <stack>#include <string.h>using namespace std;typedef struct treenode *tree;struct treenode {int item;tree left, right;};tree findtree(int in[], int pre[], int le) {//中序 前序if (!le) return NULL;tree node = (tree)malloc(sizeof(struct treenode));node->item = *pre;int i;for (i = 0; i < le; i++) {if (in[i] == *pre) break;}node->left = findtree(in, pre + 1, i);node->right = findtree(in + i + 1, pre + i + 1, le - 1 - i);return node;}int flag = 0;void bprint(tree t) {if (t) {bprint(t->left);bprint(t->right);if (!flag) flag = 1;else printf(" ");printf("%d", t->item);}}int main(){tree t = (tree)malloc(sizeof(struct treenode));stack<int>s;int pre[35], in[35];char c[5];int p1 = 0, i1 = 0,n,sum;scanf("%d", &n);sum = n;n = 2 * n;while (n--) {scanf("%s", &c);if (!strcmp(c, "Push")) {int num;scanf("%d", &num);s.push(num);pre[p1++] = num;}if (!strcmp(c, "Pop")) {in[i1++] = s.top();s.pop();}}t = findtree(in, pre, sum);bprint(t);printf("\n");return 0;}


0 0