【Openjudge】由中根序列和后根序列重建二叉树

该篇博客介绍了如何通过中根序列和后根序列来重建二叉树。文章提供了一个C++实现的算法,首先读取中根序列和后根序列,然后利用这些序列构建树结构。最后,通过深度优先搜索遍历重建后的二叉树并输出节点值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码写的比较乱,凑合看吧。
#include<iostream>
#include<stack>
#include<vector>
#include<algorithm>
using namespace std;

class node{
public:
	int num;
	node *left;
	node *right;
public:
	node(int n = 0){
		num = n;
		left = NULL;
		right = NULL;
	}
};
class Tree{
public:
	node* root;
public:
	Tree (node *n = NULL){
		root = n;
		if(n != NULL){
			root->num = n->num;
			root->left = n->left;
			root->right = n->right;
		}
	}
};

vector<int> mid;
vector<int> rev;
typedef vector<int>::iterator ite;

ite creattree(node* nroot, ite rroot, ite mleft, ite mright){
	nroot->num = *rroot;
	ite mid = find(mleft, mright, *rroot);
	ite bound  = rroot;
	if (mid != mright){
		nroot->right = new node;
		bound = creattree(nroot->right, rroot - 1, mid + 1, mright);
	}
	if ( mid != mleft){
		nroot->left = new node;
		bound = creattree(nroot->left, bound - 1, mleft, mid - 1);
	}
	return bound;
}

int main()
{
	in
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值