剑指offer系列源码-判断是否是平衡二叉树

本文详细介绍了两种判断二叉树是否为平衡树的方法,包括暴力遍历法和递归深度优先搜索法,旨在帮助读者理解平衡二叉树的概念及其判断算法。

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

解法1:

暴力遍历,时间复杂度较高。

#include <iostream>
#include<stdio.h>
using namespace std;
struct BinaryTreeNode{
    int value;
    BinaryTreeNode* left;
    BinaryTreeNode* right;
};
int treeDeep(BinaryTreeNode* root){
    if(root==NULL){
        return 0;
    }
    int left,right;
    left = treeDeep(root->left);
    right = treeDeep(root->right);
    return (left>right?left:right)+1;
}
bool isBalance(BinaryTreeNode* root){
    if(root==NULL){
        return true;
    }
    int left = treeDeep(root->left);
    int right = treeDeep(root->right);
    int diff = left-right;
    if(diff>1||diff<-1){
        return false;
    }
    return isBalance(root->left)&&isBalance(root->right);
}
int main()
{
    return 0;
}


解法二:

#include <iostream>
#include<stdio.h>
using namespace std;
struct BinaryTreeNode{
    int value;
    BinaryTreeNode* left;
    BinaryTreeNode* right;
};
bool isBalanced(BinaryTreeNode* root,int&depth){
    if(root==NULL){
        depth = 0;
        return true;
    }
    int left,right;
    if(isBalanced(root->left,left)&&isBalanced(root->right,right)){
        int diff = left - right;
        if(diff<=1&&diff>=-1){
            depth = left>right?left+1:right+1;
            return true;
        }
    }
    return false;
}
bool isBalanced(BinaryTreeNode* root){
    int depth = 0;
    return isBalanced(root,depth);
}
int main()
{
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值