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);
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,471评论 0 23
  • 有的人是刺猬 外表坚强得很,难以靠近 内心是脆弱的,一触即溃 想牢牢抓住,总是担心失去 不知道用什么方法,结果有时...
    善迪阅读 1,534评论 0 1
  • 如果这个标题吸引到你,我想你一定还会问,这个标题的言外之意有两种意思,那么我想说的到底是哪一种呢?我的回答是:刚上...
    阿愣555阅读 3,051评论 0 3
  • 2007年12月,我的第一个孩子出生,取名轩轩,一眨眼轩轩今年十岁了。2015年7月,老二YY出生,今年刚满两岁多...
    去K书银姐阅读 3,465评论 0 0