思路:求出左右子树的深度差,如果深度差的绝对值小于等于1,那么就是平衡二叉树
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot == nullptr)
return true;
int leftheight = getDepth(pRoot->left);//左子树的深度
int rightheight = getDepth(pRoot->right);//右子树的深度
if(abs(leftheight - rightheight) <= 1)
return true;
else
return false;
}
//获取树的深度
int getDepth(TreeNode * pRoot)
{
if(pRoot == nullptr)
return 0;
int left = getDepth(pRoot->left) + 1;
int right = getDepth(pRoot->right) + 1;
if(left > right)
return left;
else
return right;
}
};