Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
这个题目要求判断是否是平衡二叉树。
我们使用一个辅助函数getDeep来获取平衡二叉树当前节点的深度,有一个要求就是如果判断出当前节点下面已经不是平衡二叉树了,那么就返回-1
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int getDeep(TreeNode* root) //返回深度,并且判断是否满足平衡二叉树,不满足返回-1
{
if (!root)
return 0;
else if (!root->left && !root->right)
return 1;
int ldeep = getDeep(root->left);
int rdeep = getDeep(root->right);
if (ldeep == -1 || rdeep == -1 || abs(ldeep - rdeep) > 1)
return -1;
return max(ldeep, rdeep) + 1;
}
bool isBalanced(TreeNode* root)
{
if (getDeep(root) == -1)
return false;
return true;
}
};