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

LeetCode:Balanced Binary Tree

时间:2014-10-30 22:42:12      阅读:333      评论:0      收藏:0      [点我收藏+]

标签:algorithm   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.

思路:当树的左子树的高度与右子树的高度相差小于一,且左右子树各自都为平衡二叉树时,树为平衡二叉树。

代码:

bool Solution::isBalanced(TreeNode *root)
{
    if(root == NULL)
        return true;
    if(abs(treeHeight(root->left) - treeHeight(root->right)) > 1)
        return false;
    return isBalanced(root->left) && isBalanced(root->right);
}

int max(int a,int b)
{
    return a > b ? a : b;
}

int Solution::treeHeight(TreeNode * root)
{
    if(root == NULL)
        return 0;
    return max(treeHeight(root->left),treeHeight(root->right)) + 1;
}




LeetCode:Balanced Binary Tree

标签:algorithm   leetcode   

原文地址:http://blog.csdn.net/yao_wust/article/details/40627461

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