110. Balanced Binary Tree

Problem

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.

Example

Given the following tree [3,9,20,null,null,15,7]:

    3
   / \
  9  20
    /  \
   15   7

Return false.

Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

Return true.

Code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
static int var = [](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    int height = 0;
    bool isBalanced(TreeNode* root) {
        if(root == NULL)
            return true;
        int height = 1;
        return checkBalanced(root,height);
    }
    bool checkBalanced(TreeNode* root, int& height){
        if(!root)
            return true;
        int left_height = 0;
        int right_height = 0;
        if(!checkBalanced(root->left,left_height))
            return false;
        if(!checkBalanced(root->right,right_height))
            return false;
        if(abs(left_height-right_height)>1)
            return false;
        height = max(left_height,right_height)+1;
        return true;
        
    }
};

Result

110. Balanced Binary Tree.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 每个不平凡的人都在平凡的世界中挣扎,有人成功站起来摆脱了生活的枷锁,至于生活之外,但大部分人还是惨死在命运的车轮下...
    请叫我刘掌柜阅读 678评论 0 2
  • 那片臭海 坐轮渡50分钟便到了广东最西边的一个地级市—湛江市。以前没去过,听说也是一个很漂亮的海滨城市。按这次旅行...
    夕阳醉梦阅读 642评论 0 0
  • 简单点的理解就是:你吃得太多了,摄入能量大于消耗能量 从而型成的肥胖。 从医学角度看,肥胖是脂肪细胞数量增加和脂肪...
    小姐姐徐阅读 584评论 0 0
  • 突然微信响起了视频接受信息。点开一看,镜头中的人开头第一句就是:“怎么那么久都没有消息了。” 仔细下想想,从大三那...
    街南柳絮阅读 126评论 0 0

友情链接更多精彩内容