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;
}