Description:
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。
我最开始的错误理解是,二叉树的叶子深度差不超过1,于是我设置了一个max_depth和一个min_depth的变量来记录树的所有叶子所在深度的最大值和最小值。代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(root == nullptr)
return true;
int max = INT_MIN, min = INT_MAX, depth = 0;
findDepth(root, max, min, depth);
return (max - min) <= 1;
}
void findDepth(TreeNode* root, int& max, int& min, int depth)
{
if(root == nullptr)
{
max = (max > depth) ? max : depth;
min = (min < depth) ? min : depth;
return;
}
depth = depth + 1;
findDepth(root->left, max, min, depth);
findDepth(root->right, max, min, depth);
}
};
提交之后,测试用例出错的是下面这个:
其中,最右边的3和最左边的5的深度差已经有2了,用我的理解的代码算出来是false的,但是实际上它是可以通过的。
正确的理解是二叉树任何一个节点的两个子树,他们的深度差不超过1,对于节点1来说,左子树为5,右子树为4,符合要求;并且对于左子树来说,他的左子树比右子树也只大1;右子树亦然。这就是典型的分治思想,用递归解决非常简单。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(root == nullptr)
return true;
int differ = abs(findDepth(root->left, 1)
- findDepth(root->right, 1));
return (differ < 2) && isBalanced(root->left)
&& isBalanced(root->right);
}
int findDepth(TreeNode* root, int depth)
{
if(root == nullptr)
return depth;
return max(findDepth(root->left, depth),
findDepth(root->right, depth)) + 1;
}
};
【你必须非常努力 才能看起来毫不费力】