满二叉树和完全二叉树判定

满二叉树判断思路

若根节点高度0,根据满二叉树定义,每层(高度为high)的节点数为pow(2,high),利用该点性质,采用层序遍历,仅需判断每层的点数是否满足定义即可

代码

#include <iostream>
#include <queue>
#include <cmath>

using namespace std;

const int N = 65;

struct node{
    int l;
    int r;
} nodes[N];

int n;
int high = 0;

bool layerOrder(int root)
{
    queue<int> q;
    q.push(root);
    while(!q.empty())
    {
        int size = q.size();
        //判断每层的节点数是否满足满二叉树性质
        if(size != pow(2,high))
            return false;
        while(size--)
        {
            int temp = q.front();
            q.pop();
            if(nodes[temp].l != -1)
                q.push(nodes[temp].l);
            if(nodes[temp].r != -1)
                q.push(nodes[temp].r);
        }
        high++;
    }
    return true;
}

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

    if(layerOrder(0)) cout<<"Yes";
    else cout<<"No";

    return 0;
}

完全二叉树判断

仅需在完全二叉树的基础上稍加改一点点,先递归获得二叉树高度high;

不是完全二叉树的情况

1.在树的非最后一层中,若有一层没满,则不是完全二叉树。

2.若有左节点没有右节点,则不是完全二叉树。

#include <iostream>
#include <queue>
#include <cmath>

using namespace std;

const int N = 65;

struct node{
    int l;
    int r;
} nodes[N];

int n;
int index = 0;
int high = 0;

//获得树的高度
int getHigh(int root)
{
    if(root == -1) return 0;
    int left = getHigh(nodes[root].l);
    int right = getHigh(nodes[root].r);
    return max(left + 1,right + 1);
}

bool layerOrder(int root)
{
    queue<int> q;
    q.push(root);
    while(!q.empty())
    {
        int size = q.size();
        while(size--)
        {
            int temp = q.front();
            q.pop();
            if(nodes[temp].l != -1)
                q.push(nodes[temp].l);
            if(nodes[temp].r != -1)
                q.push(nodes[temp].r);
            //左子树为空,右子树不为空
            if(nodes[temp].l == -1 && nodes[temp].r != -1)
                return false;
        }
        //非最后一层,出现有一层没有满
        if(q.size() != pow(2,++index) && index == high + 1)
            return false;
    }
    return true;
}

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

    high = getHigh(0);
    if(layerOrder(0)) cout<<"Yes";
    else cout<<"No";

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值