满二叉树判断思路
若根节点高度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;
}