思路:递归
当前树是平衡二叉树的条件:
1、空指针
2、左子树和右子树都是平衡二叉树且左子树和右子树的深度差的绝对值小于等于1
代码
class Solution {
public:
int ComputeDepth(TreeNode* pNode){
if(pNode==nullptr) {
return 0;
}
int left_depth = ComputeDepth(pNode->left);
int right_depth = ComputeDepth(pNode->right);
return max(left_depth, right_depth)+1;
}
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot==nullptr) return true;
auto left_depth = ComputeDepth(pRoot->left);
auto right_depth = ComputeDepth(pRoot->right);
auto abs_ = abs(left_depth - right_depth);
return (abs_<=1 && IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right));
}
}; 
京公网安备 11010502036488号