美文网首页
110. Balanced Binary Tree

110. Balanced Binary Tree

作者: a_void | 来源:发表于2016-09-21 14:57 被阅读0次

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

      本文链接:https://www.haomeiwen.com/subject/disaettx.html