7-5 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.

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.

思路
参考浙大数据结构慕课讲解
观察知,其Push的顺序为先序遍历,Pop的顺序为中序遍历。先根据其顺序建立数组先序遍历数组pre[]和中序遍历数组in[],之后利用solve函数去解决。

#include<iostream>
#include<string>
using namespace std;

int * pre;int *in;int *post; 
void solve(int preL,int inL,int postL,int n);

int main()
{
	int N;
	cin>>N;
	
	pre = new int[N];
	in = new int[N];
	post = new int[N];
	
	int i1 = 0,i2 = 0;
	int MyStack[N];int top = -1;
	
	string s;
	for(int i = 0;i<2*N;i++){
		cin>>s;
		if(s[1]=='u'){
			cin>>pre[i1];
			MyStack[++top] = pre[i1];
			i1++;
		}
		if(s[1]=='o'){
			in[i2] = MyStack[top--];
			i2++;
		}
	}
	solve(0,0,0,N);
	cout<<post[0];
	for(int i = 1;i<N;i++){
		cout<<' '<<post[i];
	}
	return 0;
}

void solve(int preL,int inL,int postL,int n)//preL,inL,postL分别为三个数列的首项,n为数列的长度 
{
	int root;
	if(n==0)return;
	if(n==1){
		post[postL] = pre[preL];
		return;
	}
	root = pre[preL];
	post[postL+n-1] = root;
	int i;
	for(i = 0;i<n;i++){//求起始项到根的长度,即左半部分的长度 
		if(in[inL+i]==root){
			break;
		}
	}
	solve(preL+1,inL,postL,i);
	solve(preL+i+1,inL+i+1,postL+i,n-i-1);
}
发布了11 篇原创文章 · 获赞 0 · 访问量 128

猜你喜欢

转载自blog.csdn.net/qq_46167487/article/details/104064060
今日推荐