Skip to content

Commit

Permalink
dev hight
Browse files Browse the repository at this point in the history
  • Loading branch information
email2liyang committed Jan 8, 2019
1 parent 7c5c5c4 commit f8349a0
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -128,4 +128,21 @@ class BinarySearchTree(var root: Option[Node[Int]]) extends BinaryTree[Int] {
}

}

def hight(): Int = {
_hight(root)
}

private[this] def _hight(nodeOpt: Option[Node[Int]]): Int = {
nodeOpt match {
case None => 0
case Some(node) => {
if (node.left.isEmpty && node.right.isEmpty) {
1
} else {
scala.math.max(_hight(node.left), _hight(node.right)) + 1
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,21 @@ class BinarySearchTreeTest extends FlatSpec with Matchers {
tree.delete(18)
tree.inOrder(tree.root) should equal("1617" + nums.sorted.slice(4, nums.size).mkString(""))
tree.delete(66)
tree.inOrder(tree.root) should equal("1617" + nums.sorted.slice(4, nums.size-1).mkString(""))
tree.inOrder(tree.root) should equal("1617" + nums.sorted.slice(4, nums.size - 1).mkString(""))
}

it should "calc hight of a tree -1" in {
val tree = new BinarySearchTree(None)
val nums = Array(33, 17, 50, 13, 18, 34, 58, 16, 25, 51, 66, 19, 27, 55)
nums.foreach(tree.insert)
tree.hight() should equal(5)
}

it should "calc hight of a tree -2" in {
val tree = new BinarySearchTree(None)
val nums = Array(33, 17, 50, 13, 18, 34, 88).sorted
nums.foreach(tree.insert)
tree.hight() should equal(7)
}

}

0 comments on commit f8349a0

Please sign in to comment.