分析:抓住平衡二叉树的定义:任意一节点的左右子树高度差都小于等于1。空树也是一颗平衡二叉树。
这样,我们就可以用递归的思想了,对任意一节点,求其左子树和右子树的高度,并进行比较,若高度差大于1,则不是。否则,则递归判断其左孩子和右孩子。
注意递归退出条件,为节点为空的时候。
关于求二叉树的深度,前面有一题求过:
剑指offer_t38_二叉树的深度
代码如下:
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(!pRoot) return true;
int l_depth = Depth(pRoot->left);
int r_depth = Depth(pRoot->right);
if (abs(l_depth-r_depth)>1)
return false;
return IsBalanced_Solution(pRoot->left) &&IsBalanced_Solution(pRoot->right);
}
int Depth(TreeNode*node)
{
if(!node) return 0;
return max(Depth(node->left),Depth(node->right))+1;
}
};