二叉树

发布时间 2023-11-23 14:43:34作者: 不o凡

二叉树的遍历

点击查看代码
#include<bits/stdc++.h>
using namespace std;
const int N=150;
int parent[N];
int child[N][2];
void dfs1(int u){
	cout<<u<<' ';
	if(child[u][0]) dfs1(child[u][0]);
	if(child[u][1]) dfs1(child[u][1]);
}
void dfs2(int u){
	
	if(child[u][0]) dfs2(child[u][0]);
	cout<<u<<' ';
	if(child[u][1]) dfs2(child[u][1]);
}
void dfs3(int u){
	
	if(child[u][0]) dfs3(child[u][0]);
	if(child[u][1]) dfs3(child[u][1]);
	cout<<u<<' ';
}

int main(){
	int n;
	cin>>n;
	int S;
	cin>>S;
	for(int i=1;i<n;i++){
		int b,d;
		char c;
		cin>>b>>c>>d;
		if(c=='L') child[b][0]=d;
		else child[b][1]=d;
	}
	dfs1(S);
	cout<<'\n';
	dfs2(S);
	cout<<'\n';
	dfs3(S);
	return 0;
}

问题 B: 二叉树重构

点击查看代码
#include<bits/stdc++.h>
using namespace std;
string s1,s2;
//先序 起点 终点  中序 起点 终点 
void dfs(string first,int fl,int fr,string mid,int ml,int mr){
	if(ml>mr) return;
	int root=mid.find(first[fl]);
	dfs(first,fl+1,fl+root-ml,mid,ml,root-1);
	dfs(first,fl+root-ml+1,fr,mid,root+1,mr);
	cout<<first[fl];
}


int main(){
	cin>>s1>>s2;
	int n=s1.length();
	dfs(s1,0,n-1,s2,0,n-1);
	return 0;
}