【问题标题】:Calculating Max Imbalance of Binary Search Tree计算二叉搜索树的最大不平衡
【发布时间】:2013-04-29 14:10:52
【问题描述】:

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

}

【问题讨论】:

    标签: java recursion binary-search-tree


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-09
      • 2013-12-18
      • 1970-01-01
      • 2012-05-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多