1110 Complete Binary Tree

题目描述
知识点: 完全二叉树,层序遍历
思路: 本题为判断完全二叉树,可以先层序遍历这个树,然后依次将值填入数组中。然后利用这个数组使用完全二叉树的性质判断这个树是不是完全二叉树。(如果是的话这个数组应该是符合完全二叉树的)

#include<iostream>
#include<queue>
using namespace std;
const int N = 50;
int l[N],r[N],node[N],not_root[N];
int n;
void bfs(int u){
    int cur = 1;
    queue<int> q;
    q.push(u);
    while(!q.empty()){
        int f = q.front();
        q.pop();
        node[cur++] = f;
        if(l[f]) q.push(l[f]);
        if(r[f]) q.push(r[f]);
    }
}
int main(){
    cin>>n;
    for(int i = 1;i <= n;i++){
        string l_c,r_c;
        cin>>l_c>>r_c;
        if(l_c != "-")
        {
            int nl_c = stoi(l_c);;
            l[i] = nl_c+1;
            not_root[nl_c+1] = 1; 
        }
        if(r_c != "-"){
            int nr_c = stoi(r_c);
            r[i] = nr_c+1;
            not_root[nr_c+1] = 1; 
        }         
    }
    int root = -1;
    for(int i = 1;i <= n;i++) if(not_root[i] == 0) root = i;
    bfs(root);
    bool is_complete_tree = true;
    for(int i = 1;i <= n;i++){
        int u = node[i];
        if(u == 0) is_complete_tree = false;
        if(2*i <= n && node[2*i] != l[u]) is_complete_tree = false;
        if(2*i+1 <= n && node[2*i+1] != r[u]) is_complete_tree = false;
    }
    if(is_complete_tree)
        cout<<"YES"<<" "<<node[n]-1;
    else
        cout<<"NO"<<" "<<root-1;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值