面试题 04.04. 检查平衡性
题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/check-balance-lcci/
题目描述
实现一个函数,检查二叉树是否平衡。在这个问题中,平衡树的定义如下:任意一个节点,其两棵子树的高度差不超过 1。
示例 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 。
题目分析
自顶向下的递归
/**
* 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 height(TreeNode* root){
if(root==NULL){
return 0;
}else{
return max(height(root->left),height(root->right)) +1;
}
}
bool isBalanced(TreeNode* root) {
if(root==NULL){
return true;
}else{
return abs(height(root->left)-height(root->right))<=1 && isBalanced(root->left) && isBalanced(root->right);
}
}
};