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

时间:2013-04-29 14:10:52

标签: java recursion binary-search-tree

我目前正在编写一个递归方法来返回整个二进制搜索树的最大不平衡。我对递归编程非常陌生,因此我很难理解。 我构建的树的不平衡为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;

}

1 个答案:

答案 0 :(得分:0)

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

相关问题