题目如下:
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.
分析如下:
之前尝试一边计算深度,一边做判断,发现这是无法实现的。因为bool型的返回变量说明了返回值没有深度信息,而如果没有深度信息,那么就无法判断左子树和右子树的深度差是否为1.所以说明还要另外使用一个计算深度的函数来做辅助了。
我的代码:
看了一下,是个很正常的代码风格。
// 104ms过大集合
/**
* Definition for binary tree
* 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{
int l=height(root->left);
int r=height(root->right);
return 1+((l>r)?l:r);
}
}
bool isBalanced(TreeNode *root) {
if(root==NULL)
return true;
else{
int l,r;
l=height(root->left);
r=height(root->right);
if((l>r+1)||(r>l+1))
return false;
else
return isBalanced(root->left)&&isBalanced(root->right);
}
}
};
不过又看了一下,在leetcode官网 这里发现了一个很聪明的做法,可以把时间复杂度降低为O(N)
// 68ms过大集合
public:
int cntHeight(TreeNode *root) {
if(root == NULL) return 0;
int l = cntHeight(root->left);
int r = cntHeight(root->right);
if(l < 0 || r < 0 || abs(l-r) > 1) return -1; //自定义 return -1,表示不平衡的情况
else return max(l, r) + 1;
}
bool isBalanced(TreeNode *root) {
if(root == NULL) return true;
int l = cntHeight(root->left);
int r = cntHeight(root->right);
if(l < 0 || r < 0 || abs(l-r) > 1) return false;
else return true;
}
2014-10-09 update 上面的第二版还可以写得更简洁一些。
class Solution {
private:
int depth(TreeNode* root) {
if (root == NULL) {
return 0;
} else {
int left_depth = depth(root->left);
int right_depth = depth(root->right);
if (left_depth == -1 || right_depth == -1 || (left_depth - right_depth > 1) || (left_depth - right_depth < -1))
return -1;
else if (left_depth - right_depth > 0)
return left_depth + 1;
else return right_depth + 1;
}
}
public:
bool isBalanced(TreeNode *root) {
if (root == NULL) return true;
else return (depth(root) !=-1);
}
};