LeetCode110 给定一个二叉树,判断它是否是高度平衡的二叉树。 本题中,一棵高度平衡二叉树定义为: 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

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

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

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

/**
 * Definition for a binary tree node.
 * 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(!root)
            return true;
        // else if(!root->left&&!root->right)
        // {
        //     return true;
        // }
        // else if(root->left&&!root->right)
        // {
        //     return isBalanced(root->left)&&(abs(Depth(root->left)-Depth(root->right)) <= 1);
        // }
        // else if(!root->left&&root->right)
        //     return isBalanced(root->right)&&(abs(Depth(root->left)-Depth(root->right)) <= 1);
        else
            return isBalanced(root->left)&&isBalanced(root->right)&&(abs(Depth(root->left)-Depth(root->right)) <= 1);
    }
    int Depth(TreeNode* root)
    {
        if(!root)
            return 0;
        else
            return 1+max(Depth(root->left),Depth(root->right));
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_40906550/article/details/82470371
今日推荐