判断二叉树是否是平衡二叉树

本文介绍了一种判断二叉树是否为平衡二叉搜索树的方法。平衡二叉搜索树是一种特殊的二叉树,其左右子树高度差不超过1,且左右子树均为平衡二叉树。文章提供了插入节点和判断平衡性的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

平衡二叉搜索树(Balanced Binary Tree)具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

思路:如果一颗二叉树的所有子树都是平衡二叉树,它一定是平衡二叉树。

#include <bits/stdc++.h>
using namespace std;
typedef struct BNode* BTree;
struct BNode
{
    int data;
    BTree left;
    BTree right;
};

void Insert(BTree &t,int data){
    if(!t){
        BTree p=(BTree)malloc(sizeof(BTree));
        p->data=data;
        p->left=NULL;
        p->right=NULL;
        t=p;
    }
    else if(data<t->data)Insert(t->left,data);
    else if(data>=t->data)Insert(t->right,data);
}

bool IsBalanceTree(BTree root, int &depth)
    {
        if (root == NULL){
            depth = 0;
            return true;
        }
        int ldepth = 0,rdepth=0;
        if (!IsBalanceTree(root->left, ldepth)||!IsBalanceTree(root->right, rdepth)){
            return false;
        }
        depth = rdepth > ldepth ? rdepth + 1 : ldepth + 1;
        return abs(ldepth - rdepth) < 2;
    }
int main()
{
    int n,depth;
    int a[1001];
    cin>>n;
    BTree t=NULL;
    for(int i=0;i<n;i++){
        cin>>a[i];
        Insert(t,a[i]);
    }
    if(IsBalanceTree(t,depth))cout<<"YES"<<" "<<depth<<endl;
    else cout<<"NO"<<endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值