110. Balanced Binary Tree
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.
思路
思路很简单,递归判断左右子数的深度差是否在1以内即可。
方法一:
- 构建一个height函数,递归计算树的深度;
- 在主函数中判断节点的左右子树深度是否大于1,成立则返回false,不成立继续递归判断该节点的左右子树。
方法二:
方法一种用了两次递归判断,这里进一步优化:只要左右子树高度差大于1就直接返回false,不继续递归计算了。
c++11
方法一:
/**
* 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) return true;
if (std::abs(height(root->left) - height(root->right)) > 1) return false;
return isBalanced(root->left) and isBalanced(root->right);
}
int height(TreeNode* root) {
if (!root) return 0;
return std::max(height(root->left), height(root->right)) + 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) return true;
if (height(root) == -1) return false;
return true;
}
int height(TreeNode* root) {
if (!root) return 0;
int left_height = height(root->left);
if (left_height == -1) return -1;
int right_height = height(root->right);
if (right_height == -1) return -1;
if (std::abs(left_height - right_height) > 1) return -1;
return std::max(left_height, right_height) + 1;
}
};