题目:
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.
思路:
判断一棵树是否为平衡树可以转换为求解其两棵子树的高度差。一旦高度差大于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 == NULL) {
return true;
}
if (!isBalanced(root->left) || !isBalanced(root->right)) {
return false;
}
int left_height = getHeight(root->left);
int right_height = getHeight(root->right);
return abs(left_height - right_height) <= 1;
}
private:
int getHeight(TreeNode* root) {
if (root == NULL) {
return 0;
}
int left_height = getHeight(root->left);
int right_height = getHeight(root->right);
return max(left_height, right_height) + 1;
}
};