题目

算法思想 :我们只需要递归的判断每个根节点的左右子树高度是否小于等于1即可。
int maxDepth(TreeNode* root) {
int high = 0;
if(root == NULL)
high = 0;
else
high = max(maxDepth(root->left),maxDepth(root->right) ) + 1;
return high;
}
bool isBalanced(TreeNode* root) {
if(root == NULL)
return true;
int l_h = maxDepth(root->left);
int r_h = maxDepth(root->right);
if(abs(l_h-r_h) > 1)
return false;
else
return (isBalanced(root->left) && isBalanced(root->right) );
return true;
}
本文介绍了一种通过递归比较二叉树左右子树高度来判断二叉树是否平衡的算法。首先定义了一个辅助函数maxDepth用于计算任意节点的最大深度,然后在isBalanced函数中,利用maxDepth计算根节点的左右子树高度并比较差值是否超过1,以此判断该二叉树是否平衡。
409

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



