完全二叉树遍历题(小白)

给后序输出前序:

#include <bits/stdc++.h>

using namespace std;
#define ENDL '\n'
const int maxn = 1e6 + 10;

int n, cur;
int a[maxn], ans[maxn];

void dfs(int i) {
    if (i > n) return;
    dfs(i * 2);  //先填左子树
    dfs(i * 2 + 1);
    ans[i] = a[cur++];
}
int main() {
    cin >> n;
    for (int i = 1; i <= n; i++) cin >> a[i];
    cur = 1;
    dfs(1);
    cout << ans[1];
    for (int i = 2; i <= n; i++) cout << " " << ans[i];
    cout << ENDL;
    return 0;
}

镜像树+前序找后序:

L2-004 这是二叉搜索树吗? - 团体程序设计天梯赛-练习集 (pintia.cn)

#include<bits/stdc++.h>
using namespace std;
const int N = 1e3+10;
int a[N],n;

vector<int> ans;

void dfs1(int root,int tail){
	if(root > tail) return;
	int l = root + 1,r = tail;
	while(a[l] < a[root] && l <= tail) l++;
	while(a[r] >= a[root] && r > root) r--;
	if(l - r != 1) return;//因为要刚好越过分界线
	dfs1(root+1,r);//向左子树递归
	dfs1(l,tail);//向右子树递归
	ans.push_back(a[root]);//将当前的父节点放入答案
	//如果我们发现是一个二叉搜索树那么ans存的就是后根遍历的结果,
	//因为是递归左右子树后才放入ans中的,下面同理
}

void dfs2(int root,int tail){
	if(root > tail) return;
	int l = root + 1,r = tail;
	while(a[l] >= a[root] && l <= tail) l++;
	while(a[r] < a[root] && r > root) r--;
	if(l - r != 1) return;
	dfs2(root+1,r);
	dfs2(l,tail);
	ans.push_back(a[root]);
}

int main()
{
	ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	cin>>n;
	for(int i = 0;i < n; ++i) cin>>a[i];
	
	dfs1(0,n-1);
	if(ans.size() != n){
		ans.clear();
		dfs2(0,n-1);
	}
	if(ans.size() == n) {
	 printf("YES\n%d",ans[0]);
        for(int i = 1;i < n;i++) printf(" %d",ans[i]);

	} else {
		cout<<"NO"<<endl;
	}

	return 0;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值