Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 二叉搜索树最大不平衡度的计算_Java_Recursion_Binary Search Tree - Fatal编程技术网

Java 二叉搜索树最大不平衡度的计算

Java 二叉搜索树最大不平衡度的计算,java,recursion,binary-search-tree,Java,Recursion,Binary Search Tree,我目前正在编写一个递归方法,以返回整个二叉搜索树上的最大不平衡。我对递归编程非常陌生,所以很难理解我构建的树的不平衡度为1,但我的方法只返回0。我确信我的逻辑有缺陷 我100%确信它在方法的每个步骤中都在运行“(root==null){return 0;}”。我试着删除它并进一步定义它,它继续这样做 这是我目前的方法: public int getMaxImbalance(){ return Math.abs(getMaxImbalance(root)); } public int get

我目前正在编写一个递归方法,以返回整个二叉搜索树上的最大不平衡。我对递归编程非常陌生,所以很难理解我构建的树的不平衡度为1,但我的方法只返回0。我确信我的逻辑有缺陷

我100%确信它在方法的每个步骤中都在运行“(root==null){return 0;}”。我试着删除它并进一步定义它,它继续这样做

这是我目前的方法:

public int getMaxImbalance(){
  return Math.abs(getMaxImbalance(root));
}

public int getMaxImbalance (TreeNode<E> root){

  if (root == null){
      return 0;
  }else if(root.left != null && root.right == null){

      return 1 + getMaxImbalance(root.left) + getMaxImbalance(root.right);
              //adds 1 left is true and right is false

  }else if(root.left == null && root.right != null){

      return -1 + getMaxImbalance(root.left) + getMaxImbalance(root.right);
      //adds -1 left is false and right is true

  }

  return getMaxImbalance(root.left) + getMaxImbalance(root.right);
      //calls itself if both fields are null;

}
public int getMaxImbalance(){
返回Math.abs(getMaxImbalance(root));
}
public int getMaxImbalance(树节点根){
if(root==null){
返回0;
}else if(root.left!=null&&root.right==null){
返回1+getMaxImbalance(root.left)+getMaxImbalance(root.right);
//加1左为真,右为假
}else if(root.left==null&&root.right!=null){
return-1+getMaxImbalance(root.left)+getMaxImbalance(root.right);
//添加-1 left为false,right为true
}
返回getMaxImbalance(root.left)+getMaxImbalance(root.right);
//如果两个字段都为空,则调用自身;
}

代码中的逻辑似乎是错误的:节点的最大不平衡不是其子节点(ren)的最大不平衡之和。相反,最大不平衡应该是其子节点(ren)高度差的绝对值(如果其中一个为空,则该节点的最大不平衡值仅为0,因此当前节点的最大不平衡值完全取决于其唯一的子节点)