您的位置:首页 > 其它

4.1-判断二叉树是否平衡(same in LeetCode)

2014-08-06 16:05 465 查看
Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one.

判断二叉树是否平衡。

leetcode: http://blog.csdn.net/todorovchen/article/details/18675329

int calBf(TreeNode* root, bool& bf)
{
if(root==NULL)
return 0;
int leftHeight = calBf(root->left, bf) + 1;
int rightHeight = calBf(root->right, bf) + 1;
if(abs(rightHeight-leftHeight)>1)
{
bf=false;
return -1;
}
return max(leftHeight, rightHeight);
}
bool isBalanced(TreeNode *root)
{
bool bf = true;
calBf(root, bf);
return bf;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: