重建二叉树(已知先中)

//代码非原创,单纯做笔记便于复习

一、题目要求

给定一个一个树的先序和中序遍历结果,构建一棵树,并输出这棵树的层序遍历和后序遍历结果。注:这棵树的结点是由整数描述。

输入描述:

树结点总数m

先序输出序列

中序输出序列

输出描述:

层序输出序列

后序输出序列

二、代码

#include<bits/stdc++.h>
using namespace std;
const int maxn = 100010;
int n, preorder[maxn], inorder[maxn];
unordered_map<int, int> l,r,pos;

void build(int il, int ir, int pl, int pr){
	int root = preorder[pl];
	int k = pos[root];
	if(il < k) build(il, k - 1, pl + 1, k - 1 - il + pl + 1);//左孩子
	if(ir > k) build(k + 1, ir, k - 1 - il + pl + 1 + 1, pr);//右孩子
	cout << root << " ";//根结点
}
int _build(int il, int ir, int pl, int pr){
	int root = preorder[pl];
	int k = pos[root];
	if(il < k) l[root] = _build(il, k - 1, pl + 1, k - 1 - il + pl + 1);
	if(ir > k) r[root] = _build(k + 1, ir, k - 1 - il + pl + 1 + 1, pr);
	return root;
}
void bfs(int root){
	queue<int> q;
	q.push(root);
	while(!q.empty()){
		int t = q.front();
		cout << t << " ";
		q.pop();
		if(l.count(t)) q.push(l[t]);
		if(r.count(t)) q.push(r[t]);
	}
}
int main(){
	cin >> n;
	for(int i = 0; i < n; i++) cin >> preorder[i];
	for(int i = 0; i < n; i++){
		cin >> inorder[i];
		pos[inorder[i]] = i;
	}
	int root=_build(0,n-1,0,n-1);
	bfs(root);
	cout<<endl;
	build(0, n - 1, 0, n - 1);

	return 0;
}

三、代码图解

1.知识补充:

unordered_map:

定义:

unordered_map< key , value > m;

方法:

m.size();

m.insert(x); x 是pair

m.find(key);

m.count(key);

m.erase(key);

m[key] => value

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

int main()
{
    unordered_map<char,int> m;
    m['a']=9;
    m['?']=5;
    m['z']=99;
    m['A']=50;
    m['Z']=-2;
    m[' ']=0;
    cout<<m.size()<<endl;
    if(m.count(' ')==1)
    {
        cout<<m[' ']<<endl;
    }
    for(auto it=m.begin();it!=m.end();it++)
    {
        cout<<it->first<<" "<<it->second<<endl;
    }
    return 0;
}

2.代码解释 

后序遍历:使用递归,按左右根的顺序访问输出。 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值