题目
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) {}
};
int height(TreeNode* root)
{
if (!root)
return -1;
int hl = height(root->left);
int hr = height(root->right);
return hl > hr ? hl+1:hr+1;
}
class Solution {
public:
bool isBalanced(TreeNode* root) {
if (!root)
return true;
if (isBalanced(root->left) && isBalanced(root->right))
{
int hl = height(root->left);
int hr = height(root->right);
return hl <= hr+1 && hl >= hr-1;
}
return false;
}
};
复杂度
设结点个数为n,则树的高度为log n,有
f(n)=2f(n/2)+2log n=O(n)