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.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
#define UNBALANCED 99
#define max(a,b) (((a) > (b))?(a):(b))
int getHeight(struct TreeNode * root)
{
if(NULL == root)
return -1;
int l = getHeight(root->left);
int r = getHeight(root->right);
if(UNBALANCED == l || UNBALANCED == r || abs(l-r) > 1)
return UNBALANCED;
return 1 + max(l,r);
}
bool isBalanced(struct TreeNode* root)
{
if(NULL == root)
return true;
return getHeight(root) != UNBALANCED;
}
关于宏max的使用如果使用如下形式则存在问题
#define max(a,b) ((a) > (b))?(a):(b)
解释如下:
max(a, b) * 2
相当于:
((a) > (b))?(a):(b) * 2
((a) > (b))?(a):((b) * 2)
如果此时a>b,本来的目的是要返回2*a结果返回的是a.
C++解法
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
depth = 0;
helper(root);
return depth <= 1;
}
private:
int depth;
int helper(TreeNode* root) {
if(root == nullptr) return 0;
int l = helper(root->left);
int r = helper(root->right);
depth = max(depth,abs(l-r));
return max(l,r) + 1;
}
};
运行结果:
Runtime: 16 ms, faster than 62.70% of C++ online submissions for Balanced Binary Tree.
Memory Usage: 20.9 MB, less than 84.67% of C++ online submissions for Balanced Binary Tree.
上面代码存在的问题是程序中即使发现不是二叉平衡树程序也不会立刻结束,优化后的程序如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
balanced = true;
helper(root);
return balanced;
}
private:
bool balanced;
int helper(TreeNode* root) {
if(!balanced) return 0;
if(root == nullptr) return 0;
int l = helper(root->left);
int r = helper(root->right);
if(abs(l-r) > 1)
balanced = false;
return max(l,r) + 1;
}
};
运行结果(运行时间减少了一半):
Runtime: 8 ms, faster than 96.64% of C++ online submissions for Balanced Binary Tree.
Memory Usage: 20.7 MB, less than 97.54% of C++ online submissions for Balanced Binary Tree.