Balanced Binary Tree

Balanced Binary Tree

Total Accepted: 86508 Total Submissions: 263690 Difficulty: Easy

 

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:
    int  getTreeHeight(TreeNode* root){
        if(root==NULL){
            return 0;
        }
        int lh = getTreeHeight(root->left);
        int rh = getTreeHeight(root->right);
        return lh>rh ? lh+1:rh+1;
    }
    bool isBalanced(TreeNode* root) {
        if(root==NULL){
            return true;
        }
        int lh = getTreeHeight(root->left);
        int rh = getTreeHeight(root->right);
        if(fabs(lh-rh)<=1){
            return isBalanced(root->left) && isBalanced(root->right);
        }else{
            return false;
        }
    }
};
posted @ 2015-12-17 09:25  zengzy  阅读(159)  评论(0编辑  收藏  举报
levels of contents