题目链接
实现思路
递归处理
二叉平衡树的每一个节点的左右子树的高度差的绝对值不超过 1
所以,对所给二叉树的每个节点的左右子树进行递归判断高度,计算其平衡因子(即左右子树高度之差)。
- getDepth() 获取以当前接待为根节点的二叉树的最大深度
int getDepth(TreeNode *root, int depth) { if (root != nullptr) { // 如果节点非空,则返回左右子树中的最大深度值 return max(getDepth(root->left, depth + 1), getDepth(root->right, depth + 1)); } return depth - 1; // 节点为空,递归至此的 depth 实际上并不存在,因此返回 depth - 1 }
- judge() 对所给二叉树进行递归判断(应该也可以直接写在题目给的 isBalanced() 里面)
bool judge(TreeNode *root) { if (root != nullptr) { int left = getDepth(root->left, 1); // 获取左子树的最大深度 int right = getDepth(root->right, 1); // 获取右子树的最大深度 if (abs(left - right) > 1) { return false; } return judge(root->left) && judge(root->right); // 对左右子树进行判断,同时成立才返回 true } return true; }
实现代码(C++)
class Solution {
public:
int getDepth(TreeNode *root, int depth) {
if (root != nullptr) {
return max(getDepth(root->left, depth + 1), getDepth(root->right, depth + 1));
}
return depth - 1;
}
bool judge(TreeNode *root) {
if (root != nullptr) {
int left = getDepth(root->left, 1);
int right = getDepth(root->right, 1);
if (abs(left - right) > 1) {
return false;
}
return judge(root->left) && judge(root->right);
}
return true;
}
bool isBalanced(TreeNode* root) {
return judge(root);
}
};