您的位置:首页 > 其它

LeetCode(110) Balanced Binary Tree

2015-10-14 15:02 411 查看

题目

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.

分析

判断给定二叉树是否为二叉平衡树,即任一节点的左右子树高度差必须小于等于1,只需要求得左右子树的高度,比较判定即可。

AC代码

class Solution {
public:
//判断二叉树是否平衡
bool isBalanced(TreeNode* root) {
if (!root)
return true;

int lheight = height(root->left), rheight = height(root->right);

if (abs(lheight - rheight) <= 1)
return isBalanced(root->left) && isBalanced(root->right);
else
return false;
}
//求树的高度
int height(TreeNode *root)
{
if (!root)
return 0;
else
return max(height(root->left), height(root->right)) + 1;
}
};


GitHub测试程序源码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: