题目描述

 

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 ofevery node never differ by more than 1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int dept(TreeNode *root) {
        if(root==NULL)  return 0;
        if(root->left==NULL && root->right==NULL)
            return 1;
        return max(dept(root->left),dept(root->right))+1;
    }
     
    bool isBalanced(TreeNode *root) {
        if(root==NULL)  return true;
        int x=dept(root->left)-dept(root->right);
        if(abs(x)>1)
            return false;
        else
            return isBalanced(root->left) && isBalanced(root->right);
    }
};

  

 

posted on   王小东大将军  阅读(216)  评论(0编辑  收藏  举报
编辑推荐:
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
阅读排行:
· 对象命名为何需要避免'-er'和'-or'后缀
· JDK 24 发布,新特性解读!
· C# 中比较实用的关键字,基础高频面试题!
· .NET 10 Preview 2 增强了 Blazor 和.NET MAUI
· SQL Server如何跟踪自动统计信息更新?



点击右上角即可分享
微信分享提示