码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode110——Balanced Binary Tree

时间:2015-02-05 16:29:09      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   平衡二叉树   

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.

难度系数:

容易

实现

int getDepth(TreeNode *root)
{
    if (root == NULL) return 0; 
    if (root->left == NULL && root->right == NULL)
        return 1;
    int leftd = getDepth(root->left);
    int rightd = getDepth(root->right);
    return leftd > rightd ? leftd + 1 : rightd + 1;
}

bool isBalanced(TreeNode *root) {
    if (root == NULL) 
        return true;
    if (root->left == NULL && getDepth(root->right) <= 1)
        return true;
    if (root->right == NULL && getDepth(root->left) <= 1)
        return true;
    if ((getDepth(root->left) - getDepth(root->right)) > 1 || (getDepth(root->right) - getDepth(root->left)) > 1) {
        return false;
    }
    return isBalanced(root->left) && isBalanced(root->right);
}

LeetCode110——Balanced Binary Tree

标签:c++   leetcode   平衡二叉树   

原文地址:http://blog.csdn.net/booirror/article/details/43528591

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!