剑指offer:判定平衡二叉树

本文介绍了平衡二叉树(AVL树)的概念及其性质,通过两种方法实现判断一棵二叉树是否为平衡二叉树的算法。平衡二叉树能够有效解决二叉查找树退化成链表的问题,保持时间复杂度稳定。

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

平衡二叉树(Balanced Binary Tree)又被称为AVL树(有别于AVL算法),且具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。这个方案很好的解决了二叉查找树退化成链表的问题,把插入,查找,删除的时间复杂度最好情况和最坏情况都维持在O(logN)。但是频繁旋转会使插入和删除牺牲掉O(logN)左右的时间,不过相对二叉查找树来说,时间上稳定了很多。

题目描述:

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

总的想法: //判断根节点左右子树的深度,高度差超过1,则不平衡

方法一:

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot,int &depth){
        if(pRoot==NULL){
            depth=0;
            return true;
        }
        int ld,rd;
        bool l=IsBalanced_Solution(pRoot->left,ld);
        bool r=IsBalanced_Solution(pRoot->right,rd);
        depth=1+max(ld,rd);
       if(l&&r&&(ld>rd?ld-rd:rd-ld)<=1)
            return true;
         
        else
            return false;
        
    }
             
    bool IsBalanced_Solution(TreeNode* pRoot) {
        int depth;
        return IsBalanced_Solution(pRoot,depth);
    }
};

方法二:(单独的函数求节点深度)




public class Solution {
    //判断根节点左右子树的深度,高度差超过1,则不平衡
    public boolean IsBalanced_Solution(TreeNode root) {
        if (root==null) {
            return true;
        }
        int left = getTreeDepth(root.left);
        int right = getTreeDepth(root.right);
        return (left-right)>1?false:true;
    }
    //求取节点的深度
    public static int getTreeDepth(TreeNode root) {
        if (root==null) {
            return 0;
        }
        int leftDepth = 1+getTreeDepth(root.left);
        int rightDepth = 1+getTreeDepth(root.right);
        return leftDepth>rightDepth?leftDepth:rightDepth;
    }
}


更多文章:http://my.youkuaiyun.com/wodeqingtian1234

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值