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 PopSample 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;
}
本文介绍了一种通过栈操作实现非递归中序遍历二叉树的方法,并根据给定的Push和Pop操作序列生成对应的二叉树后序遍历序列。文章提供了完整的C++代码实现,帮助读者理解算法细节。
3537

被折叠的 条评论
为什么被折叠?



