平衡二叉树判定 AVL Balanced Binary Tree

142 篇文章 20 订阅
29 篇文章 0 订阅

题目源自于leetcode。

题目:Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

思路:

    题目给出的函数接口只有bool类型返回值。这不足以递归的判断是否平衡。因为整个树平衡与否,不仅仅是要(1)看左、右子树是否各自都是平衡的,而且还要(2)看左、右子树的高度之差是否超过1。

    所以又写了一个函数以高度作为返回值。每次递归都即判断高度差又计算树高。为了加快递归速度,一旦发现高度差超过1,就将高度置为-1,高度出现-1之后,就回一路返回到递归最外层。

   这里的返回值就既代表平衡状态值,又代表高度。当返回值是-1时,代表不平衡;当返回值时非-1时,代表平衡,此时的具体数值就是高度值。

代码:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode *root) {
        if(depth(root) == -1)
            return false;
        else
            return true;
    }
    
    int depth(TreeNode *root)
    {
        if(root == NULL)
            return 0;
        int left = depth(root->left);
        int right = depth(root->right);
        
        if (left == -1 || right == -1)
            return -1;
        else
        {
            if(abs(left - right) > 1)
                return -1;
            else
                return (left>right?left:right) + 1;
        }
    }
};


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值