110. Balanced Binary Tree(Leetcode每日一题-2020.08.17)

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 left and right subtrees of every node differ in height by no more than 1.

Example1

110. Balanced Binary Tree(Leetcode每日一题-2020.08.17)_第1张图片

Example2

110. Balanced Binary Tree(Leetcode每日一题-2020.08.17)_第2张图片

Solution

/**
 * 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;
        int leftHeight = treeHeight(root->left);
        int rightHeight = treeHeight(root->right);

        if(abs(leftHeight - rightHeight) > 1)
            return false;

        return isBalanced(root->left) && isBalanced(root->right);
        
    }

    int treeHeight(TreeNode* root)
    {
        if(!root)
            return 0;
        int leftHeight = treeHeight(root->left);
        int rightHeight = treeHeight(root->right);

        return max(leftHeight,rightHeight) + 1;
    }
};

你可能感兴趣的:(leetcode树)