1086 Tree Traversals Again(中序 先序栈 构建 后序二叉树)

1086 Tree Traversals Again (25 分)

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.

1086 Tree Traversals Again(中序 先序栈 构建 后序二叉树)
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

 /**
本题题意:
    给定一个二叉树中序遍历栈, 现在给出所有结点入栈顺序, 和所有元素的出栈顺序,
本题思路:
     入栈的顺序是 先序遍历, 出栈的顺序是 中序遍历
     只不过题目没有说明 所有结点的值都是唯一的,因此
     设定 pre, in 数组 存储 下标索引, value数组存储对应的值
本题输入时 通过判断字符的长度 通过多组输入栈 s将输入的数字下标放入pre 与 in中
            因为多组输入, 由于命令窗没有接受到命令结束符, 因此命令窗口不能看到结果
      
**/

 

#include<iostream>
#include<stack>
#include<vector>
#include<cstring>
using namespace std;
vector<int> pre, post, in, value; //存放的下标索引位置 
stack<int> s;
void post_Order(int root, int start, int end){
	if(start > end)
		return;
	else{
		int i = start;
		while(i < end && in[i] != pre[root]) i++; //如果存在相同的数据 , 此步就会出错(只会找第一个与 in[i]相等的值), 因此这里存储的是下标 
												  //并不一定是根结点索引 
		post_Order(root + 1, start, i - 1);
		post_Order(root + i - start + 1, i + 1, end);
		post.push_back(pre[root]); 
	}
}
int main(){
	int n, num, index = 0;
	scanf("%d", &n);
	char c[6];
	while(~scanf("%s", c)){ //
		if(strlen(c) == 4){
			scanf("%d", &num);
			value.push_back(num);
			s.push(index);
			pre.push_back(index++);
		}else{
			in.push_back(s.top());
			s.pop();
		}
	}
	post_Order(0, 0, n - 1);
	for(int i = 0; i < n; i++){
		printf("%d", value[post[i]]);
		if(i != n - 1){
			printf(" ");
		}
	}
	return 0;
}

 

上一篇:1086 就不告诉你 (15 分)


下一篇:PAT 甲级 1086 Tree Traversals Again