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.
这题不难,最简单的思路就是递归加上一个辅助函数求树高,树高本身也可以递归。
如下:
class Solution {
public:
bool isBalanced(TreeNode* root) {
if (root == NULL) return true;
if (!isBalanced(root->left) || !isBalanced(root->right)) return false;
if (abs(height(root->left) - height(root->right)) > 1) return false;
return true;
}
int height(TreeNode* root) {
if (root == NULL) return -1;
return max(height(root->left), height(root->right)) + 1;
}
};
缺点是这里有两个递归,有显而易见的重复计算。
可以简化为一个,对之前子树求过的树高加以利用。我们之前有种思路就是函数返回一个值,同时传递一个值,起到双管齐下的作用。代码:
class Solution {
public:
bool isBalanced(TreeNode* root) {
int height = -1;
return helper(root, height);
}
bool helper(TreeNode* root, int& height) {
if (root == NULL) return true;
int left_h = -1;
int right_h = -1;
if (!helper(root->left, left_h) || !helper(root->right, right_h)) return false;
if (abs(left_h - right_h) > 1) return false;
height = max(left_h, right_h) + 1;
return true;
}
};
当然,这种思路也可以只用一个变量解决。
class Solution {
public:
bool isBalanced(TreeNode* root) {
return helper(root) == -1 ? false : true;
}
int helper(TreeNode* root) {
if (root == NULL) return 0;
int left_h = helper(root->left);
int right_h = helper(root->right);
if (left_h == -1 || right_h == -1 || abs(left_h - right_h) > 1)
return -1;
return max(left_h, right_h) + 1;
}
};
因为false这个信息可以通过一个特殊的height设定,比如-1,来实现。而且只要出现-1,函数即可结束递归。