[各种面试题] 判断是否平衡二叉树

来源:互联网 发布:淘宝卖家开店的流程图 编辑:程序博客网 时间:2024/06/04 23:47

判断一棵二叉树是否是平衡二叉树,递归在统计深度的时候就可以返回结果了。

/*树结点的定义(请不要在代码中定义该结构)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;}