二叉树及其遍历
push为前序遍历序列,pop为中序遍历序列。将题目转化为已知前序、中序,求后序。
前序GLR 中序LGR
前序第一个为G,在中序中找到G,左边为左子树L,右边为右子树R。
将左右子树看成新的树,同理。
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
#include <iostream>
#include <cstdio>
#include <stack>
#include <string>
using namespace std; #define MaxSize 30 #define OK 1
#define ERROR 0 int preOrder[MaxSize];
int inOrder[MaxSize];
int postOrder[MaxSize]; void postorderTraversal(int preNo, int inNo, int postNo, int N); int main()
{
stack<int> stack;
int N; //树的结点数
cin >> N;
string str;
int data;
int preNo = , inNo = , postNo = ;
for(int i = ; i < N * ; i++) { //push + pop = N*2
cin >> str;
if(str == "Push") { //push为前序序列
cin >> data;
preOrder[preNo++] = data;
stack.push(data);
}else{ //pop出的是中序序列
inOrder[inNo++] = stack.top();
stack.pop(); //pop() 移除栈顶元素(不会返回栈顶元素的值)
}
}
postorderTraversal(, , , N);
for(int i = ; i < N; i++) { //输出后序遍历序列
if(i == ) //控制输出格式
printf("%d",postOrder[i]);
else
printf(" %d",postOrder[i]);
}
printf("\n");
return ;
} void postorderTraversal(int preNo, int inNo, int postNo, int N)
{
if(N == )
return;
if(N == ) {
postOrder[postNo] = preOrder[preNo];
return;
}
int L, R;
int root = preOrder[preNo]; //先序遍历GLR第一个为根
postOrder[postNo + N -] = root; //后序遍历LRG最后一个为根
for(int i = ; i < N; i++) {
if(inOrder[inNo + i] == root) { //找到中序的根 左边为左子树 右边为右子树
L = i; //左子树的结点数
break;
}
}
R = N - L - ; //右子树的结点数
postorderTraversal(preNo + , inNo, postNo, L); //同理,将左子树看成新的树
postorderTraversal(preNo + L + , inNo + L + , postNo + L, R);//同理,右子树
}