Check if a binary tree is balanced or not. This solution is from the discuss board. Much better than mine.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isBalanced(TreeNode root) {
return height(root) != -1;
}
private int height(TreeNode root)
{
if(root == null)
return 0;
int leftHeight = height(root.left);
if(leftHeight == -1)
return -1;
int rightHeight = height(root.right);
if(rightHeight == -1)
return -1;
if(Math.abs(leftHeight - rightHeight) > 1)
return -1;
return 1 + Math.max(leftHeight, rightHeight);
}
}

本文介绍了一种高效的算法来检查二叉树是否平衡。该算法通过递归地计算每个节点的高度,并比较左右子树的高度差来实现。当左右子树高度差大于1时,则认为该二叉树不平衡。
791

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



