题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
#include <cstdlib>
class Solution {
public:
//判断是不是平衡二叉树,每个子树的左右子树的高度差的绝对值不超过1
//判断左右子树的高度差 判断左子树平衡 判断右子树平衡 判断根平衡
bool IsBT(TreeNode* tree, int& dep)
{
if(tree == nullptr) return true;
int left = 0;
int right = 0;
if(IsBT(tree->left,left)&&IsBT(tree->right,right))
{
if(abs(left-right)>1)
{
return false;
}
dep = (left > right ? left:right) + 1;
return true;
}
return false;
}
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot == nullptr) return true;
int dep = 0;
return IsBT(pRoot,dep);
}
};
联想公司福利 1523人发布
查看10道真题和解析