Balanced Binary Tree (Easy)

Description

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.

Analysis

判断一个二叉树是否是平衡二叉树。即每个节点的左右子树的高度差不超过1.

My Solution

//C++
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    int dfs(TreeNode *root,int depth){
        if(root==NULL){
            return 0;
        }
        return 1+max(dfs(root->left,depth+1),dfs(root->right,depth+1));
    }
public:
    bool isBalanced(TreeNode *root) {
        if(root==NULL)
            return true;
        if(root->left==NULL&&root->right==NULL)
            return true;
        int maxl = dfs(root->left,0);
        int maxr = dfs(root->right,0);
        if(abs(maxl-maxr)>1)
            return false;
        return isBalanced(root->left) && isBalanced(root->right);
    }
};