题目:
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 ofevery node never differ by more than 1.
思路:
方法1:两个递归,一个递归求树的高度,另一个递归求左右树是否平衡。 方法2:方法1中包含两层递归,我们可以通过定义一个额外的数据结构用一个递归完成整个算法。
代码:
方法1:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root == NULL)
{
return true;
}
else
{
int l = height(root->left);
int r = height(root->right);
if(l-r >= -1 && l-r <= 1)
{
return isBalanced(root->left) && isBalanced(root->right);
}
else
return false;
}
}
int height(TreeNode *root)
{
if(root == NULL)
{
return 0;
}
else
{
if(root->left == NULL)
{
return height(root->right) + 1;
}
else if(root->right == NULL)
{
return height(root->left) + 1;
}
else
{
int l = height(root->left);
int r = height(root->right);
return l<r?(r+1):(l+1);
}
}
}
};
方法2:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct SubTreeInfo{
int height;
bool isBalanced;
SubTreeInfo(int height, bool isBalanced): height(height), isBalanced(isBalanced) {};
};
class Solution {
public:
bool isBalanced(TreeNode *root) {
SubTreeInfo r = balanced(root);
return r.isBalanced;
}
SubTreeInfo balanced(TreeNode* node){
if(node == NULL){
return SubTreeInfo(0, true);
}
else{
SubTreeInfo left = balanced(node->left);
SubTreeInfo right = balanced(node->right);
int h = (left.height > right.height ? left.height : right.height) + 1;
bool b = left.isBalanced && right.isBalanced;
b = b && ((left.height - right.height >= -1) && (left.height - right.height <= 1));
return SubTreeInfo(h, b);
}
}
};