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.

 

 

class Solution {
public:

    int depth(TreeNode* root) {
        if (root == nullptr) return 0;
        return 1 + max(depth(root->left),depth(root->right));
    }
    bool isBalanced(TreeNode* root) {
        if(root == nullptr) return true;

        bool left = isBalanced(root->left);
        bool right = isBalanced(root->right);
        return left && right && abs(depth(root->left)-depth(root->right)) <=1;
    }
};

 

 

 1 class Solution {
 2     public boolean isBalanced(TreeNode root) {
 3         if(root==null) return true;
 4         int left = depth(root.left);
 5         int right = depth(root.right);
 6         return Math.abs(left-right)<=1 && isBalanced(root.left) && isBalanced(root.right);
 7     }
 8     private int depth(TreeNode root){
 9         if(root==null) return 0;
10         return Math.max(depth(root.left),depth(root.right))+1;
11     }
12 }

 

posted @ 2017-10-31 13:56  乐乐章  阅读(96)  评论(0编辑  收藏  举报