输入一棵二叉树,判断该二叉树是否是平衡二叉树。
递归
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null)
return true;
int left = depth(root.left);
int right = depth(root.right);
if(Math.abs(left-right) > 1)
return false;
return true;
}
private int depth(TreeNode root)
{
if(root == null)
return 0;
int left = depth(root.left);
int right = depth(root.right);
return (left > right) ? (left+1) : (right+1);
}
本文介绍了一种通过递归算法来判断二叉树是否为平衡二叉树的方法。主要思路是先计算左子树和右子树的高度,如果两者的高度差大于1,则认为该二叉树不平衡。
1190

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



