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 binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool bRes;
int depth(TreeNode* root)
{
if (0 == root) return 0;
if (0 == root->left && 0 == root->right)
return 1;
int depthL = depth(root->left);
int depthR = depth(root->right);
if (abs(depthL - depthR) > 1)
bRes = false;
return depthL > depthR ? 1 + depthL : 1 + depthR;
}
bool isBalanced(TreeNode *root)
{
bRes = true;
depth(root);
return bRes;
}
};
说点自己的感觉,一开始做这道题稍微有点想法就忙去写代码,导致提交三次都错误,后来搞明白自己一直没有一个确定的思路,然后做完另一道题后,具体扎扎实实的总结了这道题,应该用什么思路,算法,结果得出,在递归求depth过程中,比较左右子树depth之差。
本文深入探讨了如何使用递归方法来判断给定的二叉树是否为平衡二叉树,通过计算每个节点的左右子树深度,并确保其差值不超过1,实现对树结构的高效验证。
941

被折叠的 条评论
为什么被折叠?



