题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pRoot TreeNode类
* @return bool布尔型
*/
bool IsBalanced_Solution(TreeNode* pRoot) {
auto hei = [](auto&& hei, TreeNode* n, size_t h) -> size_t {
if (not n) return h;
else return std::max(hei(hei, n->left, h), hei(hei, n->right, h)) + 1;
};
auto IsBal = [&hei](auto&& IsBal, TreeNode* node) -> bool {
if(not node) return true;
return std::abs<int>(hei(hei, node->left, 0) - hei(hei, node->right, 0)) <= 1 and IsBal(IsBal, node->left) and IsBal(IsBal, node->right);
};
return IsBal(IsBal, pRoot);
}
};


联想公司福利 1512人发布