题目描述
给定一个二叉树,判断它是否是 平衡二叉树
解题思想
使用递归依次计算左子树的高度和右子树的高度
代码
cpp
class Solution {
public:
int height(TreeNode* node) {
if (node == nullptr) return 0;
int leftT = height(node->left);
if (leftT == -1) return -1;
int rightT = height(node->right);
if (rightT == -1) return -1;
if (abs(leftT - rightT) > 1)
return -1;
else
return 1 + max(leftT, rightT);
}
bool isBalanced(TreeNode* root) {
return height(root) == -1 ? false : true;
}
};