示例1
输入:
{1,2,3,4,5,6,7}
返回值:
true
示例2
输入:
{}
返回值:
true
代码
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
*
* @param pRoot TreeNode类
* @return bool布尔型
*/
#include <math.h>
bool flag = true;
int dfs(struct TreeNode* pRoot) {
if (!pRoot)return 0;
//计算左子树的高度
int left = dfs(pRoot->left) + 1;
//计算右子树的高度
int right = dfs(pRoot->right) + 1;
//判断左右两个子树的高度差的绝对值是否超过1
flag = flag && (abs(left - right) <= 1);
//返回左右子树的最高高度
return left > right ? left : right;
}
bool IsBalanced_Solution(struct TreeNode* pRoot ) {
// write code here
if (!pRoot) return true;
dfs(pRoot);
return flag;
}
``