ACWING--1589. 构建二叉搜索树AcWing 1600. 完全二叉树

AcWing 1589

这个题是对树的遍历进行巩固,这个题用到了树的中序遍历的变形,然后使用层序遍历对树节点的权值进行输出

#include<bits/stdc++.h>
using namespace std;

const int N = 100010;

int l[N],r[N];
int a[N];
int w[N],q[N];

void dfs(int u, int& k)
{
	if(u == -1)
		return;
	dfs(l[u],k);
	w[u]=a[k++];
	dfs(r[u],k);
}

void bfs()
{
	int hh=0,tt=0;
	q[0]=0;
	q[1]=1;
	while(hh<=tt)
	{
//		cout<<hh<<endl;
		int t=q[hh++];
//		cout<<t <<endl;
//		cout<<hh;
//		exit(-1);
		cout<<w[t]<<" ";
		if(l[t]!=-1) q[++tt]=l[t] ;
		if(r[t]!=-1) q[++tt]=r[t] ;
	}
}

int main()
{
	int n;
	cin>>n;
	for(int i = 0 ;  i < n ; i ++ )
	{
		cin>>l[i]>>r[i];
	}

	for(int i = 0 ;  i < n ; i ++ )
	{
		cin>>a[i];
	}
	sort ( a ,a + n );
	int k=0;
	dfs(0,k);
	bfs();
	return 0;
}

AcWing 1600

完全二叉树就是节点的总数等于最后一层最后一个数的标号

1. 看清YES的情况需要输出最后一个节点, NO的话是输出根节点
2. 一定要注意节点编号可能是两位数,用char读的话就凉了(我就是这么干的...查了好久),stoi函数
3. 思路:l r数组存储树, 在第一次读取数据的时候找出父节点
         填数据,从根节点开始遍历,如果是完全二叉树,刚好可以填进1-n (根节点位置是1)
         否则最后一个节点的位置一定大于n
#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;

const int N = 60;

int l[N], r[N], max_k;
bool has_father[N];
int n, lastu;

void dfs(int root, int k)
{
    if(max_k < k)
    {
        lastu = root;
        max_k = k;
    }
    if(l[root] != -1) dfs(l[root], 2 * k);     //左孩子
    if(r[root] != -1) dfs(r[root], 2 * k + 1); //右孩子
}

int main()
{
    cin >> n;
    memset(l, -1, sizeof l);
    memset(r, -1, sizeof r);
    for(int i = 0; i < n; i ++)
    {
        string a, b;
        cin >> a >> b;
        if(a != "-") l[i] = stoi(a), has_father[l[i]] = true;
        if(b != "-") r[i] = stoi(b), has_father[r[i]] = true;
    }
    int root = 0;
    while(has_father[root]) root ++;

    dfs(root, 1);
    if(max_k > n) cout << "NO " << root << endl;
    else cout << "YES " << lastu << endl;
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值