KY212 二叉树遍历

本文介绍了一个使用C++编写的函数,通过前序和中序遍历序列构建二叉树,利用递归方法实现节点的左、右子树分配。
摘要由CSDN通过智能技术生成

前序+中序得出二叉树,靠着回忆推出的板子
ti

#include<bits/stdc++.h>

using namespace std;

struct tree{
	char c;
	tree *left, *right;
	tree(char x):c(x), left(NULL), right(NULL){};
};

string s1, s2;
int n, m;
int t;
int a[110];

tree* build(char x){
	tree *root;
	root->c = x;
	root->left = NULL;
	root->right = NULL;
}

tree* Build(int pre, int in, int len){  //分别表示前序序列开始的位置,中序序列开始的位置,长度 
	if(len == 1){
		tree *root = new tree(s1[pre]);
		return root;
	}
	tree *root = new tree(s1[pre]);
	for(int i = 0; i < len; i ++ ){
		if(s2[i + in] == s1[pre]){
			if(i != 0) root->left = Build(pre + 1, in, i);
			else root->left = NULL;
			if(pre + i + 1 < pre + len) root->right = Build(pre + i + 1, in + i + 1, len - i - 1);
			else root->right = NULL;
			break;
		}
	} 
	return root;
}

void houxu(tree *root){
	if(root == NULL) return ;
	if(root->left != NULL) houxu(root->left);
	if(root->right != NULL) houxu(root->right);
	cout<<root->c;
	return ;
}

int main()
{
	while(cin>>s1>>s2){
		tree *root = Build(0, 0, s1.length());
		houxu(root);
		cout<<endl;
	}
	return 0;
}
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值