难度Easy
原题连接
内容描述
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.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
思路 - 时间复杂度: O(n)- 空间复杂度: O(1)******
判断有个平衡二叉树,我们只要先求出左右子树的高度差,判断是否大于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:
bool isBalanced(TreeNode* root) {
if(root == nullptr)
return true;
return abs(height(root ->left) - height(root ->right)) <= 1 && isBalanced(root ->left) && isBalanced(root ->right);
}
int height(TreeNode* root){
if(root == nullptr)
return 0;
return max(height(root ->left),height(root ->right)) + 1;
}
};