isSemiBalanced()Java BST方法未通过测试

时间:2015-07-27 01:58:48

标签: java scala recursion intellij-idea binary-search-tree

我正在使用Intellij IDEA并正在测试我的BST以查看它是否是半平衡的。半平衡(至少在此项目中指定)意味着树中的每个节点都是半平衡的:

一个有0个孩子的节点是半完美的。

有一个孩子的节点不是半完美的。

如果(孩子的大小<=小孩子的大小* 3),有2个孩子的节点是半完美的

我在eclipse中实现了以下代码。它通过我抛出的所有BST,但它不会通过Intellij IDEA中的这个测试。我已经在下面包含了我的方法(在运行main()函数时可以在Eclipse中运行)以及我的方法必须在IDEA中传递的测试(它没有,并且目前是我的问题)。测试是用Scala编写的。多谢你们。

  //My Java method and helper method
  public static boolean isSemiBalanced (Node t) {
    int n = isSemiBalancedInt(t);
    if (n <= -1) return false;
    return true;
  }

  private static int isSemiBalancedInt(Node node) {
    if (node == null) return 1;
    if (node.left == null && node.right == null) return 0;
    else if (node.left == null || node.right == null) return -1;
    else {
      int sizeMax = Math.max(isSemiBalancedInt(node.left), isSemiBalancedInt(node.right));
      int sizeMin = Math.min(isSemiBalancedInt(node.left), isSemiBalancedInt(node.right));
      if (sizeMax == -1 || sizeMin == -1) return -1;
      if (sizeMax <= 3 * sizeMin) return isSemiBalancedInt(node.left) + isSemiBalancedInt(node.right);
    }
    return -1;
  }


//Scala code that checks my Java method
import org.scalatest._
import org.scalacheck.Gen

class hw1tests extends UnitSpec {
  val EX : Map[Int, Tag] = 
    (for (i <- (1 to 12).toList) yield {
      object T extends Tag ("hw1ex%02d".format (i))
      (i, T)
    }).toMap

  import hw1._
  import hw1.NodeSamples._
  import stdlib._

  val trees : List[Node] = List (t01, t02, t03, t04, t05, t06, t07, t08, t09, t10)
  val treesCopy : List[Node] = for (t <- trees) yield NodeOps.copy (t)

  def compareToDepth (t1 : Node, t2 : Node, k : Int) : Boolean = {
    if (k < 0) {
      true
    } else if ((t1 eq null) || (t2 eq null)) {
      t1 eq t2
    } else {
      (t1.key == t2.key) && compareToDepth (t1.left, t2.left, k - 1) && compareToDepth (t1.right, t2.right, k - 1)
    }
  }

  def traversal (t : Node) : List[Int] = {
    if (t eq null) {
      Nil
    } else {
      traversal (t.left) ++ List (t.key) ++ traversal (t.right)
    }
  }

  def noChange () = {
    for ((t1, t2) <- trees.zip (treesCopy)) {
      assert (compareToDepth (t1, t2, 10) === true)
    }
  }

  property ("EX09 - isSemiBalancedTest", EX (9)) {
    val sizeTable = Table (
      ("t", "isSemiBalanced (t)"),
      (t01,  true),
      (t02, false),
      (t03, false),
      (t04,  true),
      (t05,  true),
      (t06, false),
      (t07,  true),
      (t08,  true),
      (t09,  true),
      (t10,  true)
    )
    forAll (sizeTable) { (t : Node, res : Boolean) =>
      assert (NodeOps.isSemiBalanced (t) ===  res)
    }
    noChange
  }

0 个答案:

没有答案