0

I'm doing the exercise on leetcode using Scala. The problem I'm working on is "Maximum Depth of Binary Tree", which means find the maximum depth of a binary tree.

I've passed my code with IntelliJ, but I keep having compile error(type mismatch) when submitting my solution in Leetcode. Here is my code, is there any problem or any other solution please?

object Solution {
abstract class BinTree
case object EmptyTree extends BinTree
case class TreeNode(mid: Int, left: BinTree, right: BinTree) extends BinTree

  def maxDepth(root: BinTree): Int = {
    root match {
      case EmptyTree => 0
      case TreeNode(_, l, r) => Math.max(maxDepth(l), maxDepth(r)) + 1
    }
  }
}

The error is here : Line 17: error: type mismatch; Line 24: error: type mismatch; I know it is quite strange because I just have 13 lines of codes, but I didn't made mistakes, trust me ;)

6
  • 2
    Can you post the full error message? Commented Aug 14, 2017 at 15:32
  • Line 17: error: type mismatch; Line 24: error: type mismatch; Commented Aug 14, 2017 at 15:37
  • Your code has no 17th line. Maybe add some line numbers so we can see what the error message refers to. Commented Aug 14, 2017 at 15:44
  • Is your code working locally on your computer? Commented Aug 14, 2017 at 15:46
  • TreeNode is defined for you. You're stepping on the supplied code by trying to redefine it. Commented Aug 14, 2017 at 16:04

1 Answer 1

3

This looks like an error specific of the leetcode problem. I assume you're referring to https://leetcode.com/problems/maximum-depth-of-binary-tree/description/

Perhaps you're not supposed to re-implement the data structure but just to provide the implementation for maxDepth, i.e. TreeNode is already given. Try this:

object Solution {
    def maxDepth(root: TreeNode): Int = {
        if (root == null) {
            0
        } else {
            Math.max(maxDepth(root.left), maxDepth(root.right)) + 1
        }
    }
}

This assumes that the TreeNode data structure is the one given in the comment:

/**
 * Definition for a binary tree node.
 * class TreeNode(var _value: Int) {
 *   var value: Int = _value
 *   var left: TreeNode = null
 *   var right: TreeNode = null
 * }
 */
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.