示例 1:
给定二叉树 [3,9,20,null,null,15,7]
3 / \ 9 20 / \ 15 7
返回 true
。
示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]
1 / \ 2 2 / \ 3 3 / \ 4 4
返回 false
。
限制:
0 <= 树的结点个数 <= 10000
解析:
这道题通过递归计算每一个结点的深度,结点的深度是左右结点的深度最大值+1,然后判断左右结点的深度差的绝对值是否在1以内,如果不是,则证明该二叉树并非平衡二叉树,直接返回-1即可。
源码:
class Solution {
public:
bool flag = true;
int function (TreeNode* root) {
if (root == NULL) {
return 0;
}
int leftLength = function(root->left);
if (leftLength == -1) {
return -1;
}
int rightLength = function(root->right);
if (rightLength == -1) {
return -1;
}
//cout << root->val << "-" << leftLength << "-" << rightLength << endl;
if (abs(leftLength - rightLength) <= 1) {
return 1 + max(leftLength, rightLength) ;
} else {
return -1;
}
}
bool isBalanced(TreeNode* root) {
if (root == NULL) {
return true;
}
if (function(root) == -1) {
return false;
} else {
return true;
}
}
};