题目描述:
输入一棵二叉树,判断该二叉树是否是平衡二叉树
分析:
合理设计函数参数,记录树的深度,避免搜索重复节点。
代码:
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
int depth=0;
return IsBalanced(pRoot,depth);
}
bool IsBalanced(TreeNode *pRoot,int& depth){
if(pRoot==NULL){
depth=0;
return true;
}
int left=0,right=0l;
if(IsBalanced(pRoot->left,left)&&IsBalanced(pRoot->right,right)){
int dif=right-left;
if(dif>=-1&&dif<=1){
depth=1+(left>right?left:right);
return true;
}
}
return false;
}
};