题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
思路
//从根节点开始判断是不是左右子树高度差距在-1到1之间
code
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
int depth=0;
return IsBalanced(pRoot,depth);
}
bool IsBalanced(TreeNode*pRoot,int &depth){
if(pRoot==nullptr){
depth=0;
return true;
}
int left,right;
if(IsBalanced(pRoot->left,left)&&IsBalanced(pRoot->right,right)){
int dif=left-right;
if(dif>=-1&&dif<=1){
depth=1+(left>right?left:right);
return true;
}
}
return false;
}
};