首页 > 其他分享 >浙大数据结构慕课课后题(03-树3 Tree Traversals Again)

浙大数据结构慕课课后题(03-树3 Tree Traversals Again)

时间:2024-09-09 22:21:10浏览次数:11  
标签:03 课课 preL int inL ++ postL solve Again

题目翻译:

题解: 

        

#include<bits/stdc++.h>
using namespace std;

void CreatTree();
void solve(int preL, int inL, int postL, int n);

int Pre[35],In[35],Post[35];
int	N; 

int main(){
	cin>>N;
	getchar();
	CreatTree();		
	solve(0,0,0,N);
	for(int i = 0; i < N; i++) {
		cout<<Post[i];	
		if(i != N-1)
		cout<<" ";
	}
}

void CreatTree(){
	int pre = 0,in = 0; 
	stack<int> st;
	for(int i = 0; i < N*2; i++){
		string str;
		cin>>str;
		if(str == "Push"){
			int num;
			cin>>num;
			st.push(num);
			Pre[pre++] = num;	
		}
		else{
			int top = st.top();
			st.pop();
			In[in++] = top;
		}
	}
}

void solve(int preL, int inL, int postL, int n){
	int i,root,L,R;
	if(n == 0)
	return; 
	if(n == 1){
		
		Post[postL] = Pre[preL];
		return;
	}
	root = Pre[preL];
	Post[postL+n-1] = root;
	for(i = 0;i < n; i++){
		if(In[inL+i] == root) 
		break;
	} 
	L = i; R = n-L-1;
	solve(preL+1,inL,postL,L);
	solve(preL+L+1,inL+L+1,postL+L,R);
}



 

标签:03,课课,preL,int,inL,++,postL,solve,Again
From: https://blog.csdn.net/Charon_super/article/details/142071054

相关文章