1086 Tree Traversals Again
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:
6 Push 1 Push 2 Push 3 Pop Pop Push 4 Pop Pop Push 5 Push 6 Pop Pop
Sample Output:
3 4 2 6 5 1
题意
通过使用栈可以以非递归方式实现二叉树的中序遍历。
例如,假设遍历一个如下图所示的 6 66 节点的二叉树(节点编号从 1 11 到 6 66)。
则堆栈操作为:push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop() 。
我们可以从此操作序列中生成唯一的二叉树。
你的任务是给出这棵树的后序遍历。
思路
可以从用栈实现二叉树的中序遍历的思路中找到规律:
如果上一次操作是 Push ,则当前 Push 的结点是其父结点的左孩子,这里的父结点是上次 Push 的结点。例如,push(1); push(2); ,则结点 2 是上次 Push 的结点 1 的左孩子。
如果上一次操作是 Pop ,则当前 Push 的结点是其父结点的右孩子,这里的父节点是上次 Pop 的结点。例如,push(1); push(2); push(3); pop(); pop(); push(4); ,结点 4 是上次 Pop 的结点 2 的右孩子。
如果上一次没有操作,则当前 Push 的结点就是根结点。
代码
#include<bits/stdc++.h> using namespace std; const int N = 40; int n; int l[N], r[N]; //用哈希表来存储每个结点左孩子的下标 void dfs(int u, int root) { if (!u) return; dfs(l[u], root); dfs(r[u], root); cout << u; if (u != root) cout << " "; //最后一个结点输出末尾不能加空格 } int main() { int last = 0, type, root; stack<int> stk; cin >> n; for (int i = 0; i < n * 2; i++) { string op; cin >> op; if (op == "Push") { int x; cin >> x; if (!last) root = x; //第一个结点为根结点 else //设置父结点的左右孩子 { if (type == 0) l[last] = x; //上个操作是Push else r[last] = x; //上个操作是Pop } last = x; type = 0; //表示Push stk.push(x); } else { last = stk.top(); stk.pop(); type = 1; //表示Pop } } dfs(root, root); //后序遍历 return 0; }