题目(力扣):
观察题目,发现最重要的条件就是,两颗子树的高度差的绝对值不超过1,我们就可以用递归将所有左子树和右子树都遍历一个,求出他们的高度差,若差值 > 1,则返回false,否则则继续遍历。
再次之前,写一个辅助函数会使你的代码更简洁而且条理也更清晰:
TreeHeight:
int TreeHeight(struct TreeNode* root)
{if(!root)return 0;int left = TreeHeight(root->left);int right = TreeHeight(root->right);return left > right ? left + 1 : right + 1;
}
接着就可以按照上面分析的思路走,很快就能解决:
bool isBalanced(struct TreeNode* root) {if(!root)return true;int sub = abs(TreeHeight(root->left)-TreeHeight(root->right));if(sub > 1)return false;return isBalanced(root->left) && isBalanced(root->right);
}
提交结果:
完整代码:
int TreeHeight(struct TreeNode* root)
{if(!root)return 0;int left = TreeHeight(root->left);int right = TreeHeight(root->right);return left > right ? left + 1 : right + 1;
}
bool isBalanced(struct TreeNode* root) {if(!root)return true;int sub = abs(TreeHeight(root->left)-TreeHeight(root->right));if(sub > 1)return false;return isBalanced(root->left) && isBalanced(root->right);
}