110. Balanced Binary Tree

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.

/**
 * 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:
    inline int max(int a, int b){
        return a > b ? a : b;
    }
    inline int abs(int x){
        return x >= 0 ? x : -x;
    }
    int subtreeDepth(TreeNode* root){
        if(NULL == root) return 0;
        else return 1 + max(subtreeDepth(root->left), subtreeDepth(root->right));
    }
    
    bool isBalanced(TreeNode* root) {
        if(NULL == root) return true;
        return abs(subtreeDepth(root->left) - subtreeDepth(root->right)) <= 1 &&
               isBalanced(root->left) && 
               isBalanced(root->right);
    }
};

你可能感兴趣的:(110. Balanced Binary Tree)