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;
}