首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >leetcode 110-判断一棵树是否为平衡二叉树 #算法#

leetcode 110-判断一棵树是否为平衡二叉树 #算法#

作者头像
梦飞
发布2022-06-23 11:24:08
发布2022-06-23 11:24:08
3830
举报
文章被收录于专栏:csdn文章同步csdn文章同步

原题如下

Given a binary tree, determine if it is height-balanced. 给出一棵二叉树,判断它是否高度平衡。 For this problem, a height-balanced binary tree is defined as: 高度平衡二叉树定义为:

代码语言:javascript
复制
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
任何节点的两棵子树的深度差不能大于一。

换个说法就是,左右子树的高度(深度)差不能超过一并且左右子树也是平衡二叉树。

思路

首先需要计算一棵树的深度,一棵树的深度为其左右子树的较大深度加上一,左右子树的深度也可以用同样的方法计算出,可以用递归实现,终止条件是根节点为空时深度为0; 有了深度之后,就可以比较某一节点的左右子树的深度差是否小于等于1,并要求左右子树也是平衡树,同样可以用递归实现,终止条件是空树是平衡树。

代码

代码语言:javascript
复制
class Solution {
public:
    int depth(TreeNode* root){
        if(root == NULL) return 0;
        int leftDepth = depth(root->left);
        int rightDepth = depth(root->right);
        return (leftDepth > rightDepth ? leftDepth : rightDepth) + 1;
    }
    
    bool isBalanced(TreeNode* root) {
        if(root == NULL) return true;
        return abs(depth(root->left) - depth(root->right)) <= 1 
            && isBalanced(root->left) 
            && isBalanced(root->right);
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-10-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 原题如下
  • 思路
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档