- 思路
计算左右子树的高度差,使用后续遍历计算输的高度,(前序遍历计算树的深度)
int getHeight(TreeNode* cur)//获取二叉树的高度
{
if(cur == nullptr)
{
return 0;
}
int leftHeight = getHeight(cur->left);//左
if(leftHeight == -1)
{
return -1;
}
int rightHeight = getHeight(cur->right);//右
if(rightHeight == -1)
{
return -1;
}
if(abs(leftHeight - rightHeight) > 1)//计算左右两节点高度差
{
return -1;
}
else
{
return 1 + max(leftHeight, rightHeight);
}
}
bool isBalanced(TreeNode* root)
{
return getHeight(root) == -1 ? false : true;//计算二叉树的深度,用前序遍历,高度则用后序遍历
}```
参考:
https://programmercarl.com/0110.%E5%B9%B3%E8%A1%A1%E4%BA%8C%E5%8F%89%E6%A0%91.html#%E9%80%92%E5%BD%92