题解 | #判断是不是平衡二叉树#比官方的代码形式简单
判断是不是平衡二叉树
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) {
// write code here
int depth = 0;
return judge(pRoot, depth);
}
bool judge(TreeNode* root, int& depth)
{
if(root == nullptr)
{
depth = 0;
return true;
}
int left = 0;
int right = 0;
bool lb = judge(root->left, left);
bool rb = judge(root->right, right);
depth = left > right ? left + 1 : right + 1;
return (left - right <= 1) && (left - right >= -1) && lb && rb;
}
};
另一个代码
/**
* 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) {
// write code here
if(pRoot == nullptr)
return true;
int left = deep(pRoot->left);
int right = deep(pRoot->right);
if((left - right <= 1) && (left - right >= -1) &&
IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right))
return true;
else
return false;
}
int deep(TreeNode* root)
{
if(root == nullptr)
return 0;
int left = deep(root->left);
int right = deep(root->right);
return left > right ? left + 1 : right + 1;
}
};



查看14道真题和解析