110. 平衡二叉树

发布时间 2023-04-05 20:40:17作者: xiazichengxi

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。

class Solution {
public:
    int get_son_depth(TreeNode* root){
        if(root == nullptr) return 0;
        int l = get_son_depth(root->left);
        if(l == -1) return -1;
        int r = get_son_depth(root->right);
        if(r == -1) return -1;
        return abs(l-r)>1 ? -1: 1 + std::max(l,r);
    }
    bool isBalanced(TreeNode* root) {
        return get_son_depth(root) == -1 ? false:true;
    }
};