Java 检查树是否平衡时发生断言错误
我有一棵二叉树,我想检查这棵树是否平衡。我有以下代码:Java 检查树是否平衡时发生断言错误,java,data-structures,binary-tree,binary-search-tree,Java,Data Structures,Binary Tree,Binary Search Tree,我有一棵二叉树,我想检查这棵树是否平衡。我有以下代码: public boolean isBalanced(){ return balanced(root); } public boolean balanced(Node current){ int leftHeight; int rightHeight; if(current == null){ return true;
public boolean isBalanced(){
return balanced(root);
}
public boolean balanced(Node current){
int leftHeight;
int rightHeight;
if(current == null){
return true;
}
leftHeight = height(current.left);
rightHeight = height(current.right);
if(leftHeight - rightHeight <= 1){
return true;
}
return false;
}
int height(Node node)
{
/* base case tree is empty */
if (node == null)
return 0;
/* If tree is not empty then height = 1 + max of left
height and right heights */
return 1 + Math.max(height(node.left), height(node.right));
}
public boolean isBalanced(){
返回平衡(根);
}
公共布尔平衡(节点当前){
int-leftHeight;
整数右高;
如果(当前==null){
返回true;
}
leftHeight=高度(当前.左侧);
rightHeight=高度(当前.右侧);
如果(leftHeight-rightHeight,根据,平衡二叉树的定义是,平衡二叉树是一种二叉树结构,其中每个节点的左右子树的高度差不超过1
在代码中,您正在检查
if(leftHeight - rightHeight <= 1){
return true;
}
if(leftHeight-rightHeight,因为只有当右节点和左节点的高度相同(或相差1)时,树才是不平衡的)可能是我错了或误解了什么,但这不是什么吗“leftHeight-rightHeight否,balanced表示右侧节点和左侧节点上的节点数相同,并且每个子节点的高度相同(或最多左侧高出右侧的1)。哦,你说得对,谢谢