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:
    bool isBalance(TreeNode* root, int &dep) {
        if (root == NULL) {
            dep = 0;
            return true;
        }
        int l ,r;
        int left = 0,right = 0;
        l = isBalance(root->left,left);
        r = isBalance(root->right,right);
        if (l && r) {
            dep = max(left, right) + 1;
            if (abs(left - right) <= 1) return true;
            return false;
        }
        else return false;
    }
    bool isBalanced(TreeNode* root) {
        int dep = 0;
        if (root == NULL) return true;
        if (isBalance(root, dep)) return true;
        return false;
    }
};

 

posted on 2017-07-24 10:48  Beserious  阅读(123)  评论(0编辑  收藏  举报