判断一棵二叉树是否是平衡二叉树,递归在统计深度的时候就可以返回结果了。
/*
树结点的定义(请不要在代码中定义该结构)
struct TreeNode {
TreeNode *left;
TreeNode *right;
}*/
bool _isBalanced(TreeNode* root,int& depth);
bool isBalancedTree(TreeNode *root) {
if (!root )
return true;
int depth=0;
return _isBalanced(root,depth);
}
bool _isBalanced(TreeNode* root,int& depth)
{
if (!root )
{
depth=0;
return true;
}
int lDepth=0,rDepth=0;
if ( !_isBalanced(root->left,lDepth))
return false;
if (!_isBalanced(root->right,rDepth))
return false;
if ( abs(lDepth-rDepth) >1 )
return false;
depth=max(lDepth,rDepth)+1;
return true;
}