题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
使用后序遍历记录深度的方式,避免重复遍历
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
int depth=0;
return helper(pRoot, depth);
}
private:
bool helper(TreeNode* pRoot, int &Depth){
if (pRoot == NULL){
Depth = 0;
return true;
}
int left, right;
if (helper(pRoot->left, left) && helper(pRoot->right, right)){
Depth = max(left, right) + 1;
int dif = left - right;
if (dif <= 1 && dif >= -1){
return true;
}
}
return false;
}
};