For a binary search tree I need to compute the length of the diameter of the tree. I need some inputs for scala program

独自空忆成欢 提交于 2020-03-06 11:08:30

问题


The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. Here is my logic in scala.

Can anyone check the logic and confirm if there is a simpler method.

Also I am seeing this error when I run the program:

error: not found: value Solution (in solution.scala) var ret = Solution.diameterOfBinaryTree(param1)

class Solution {

  var ans: Int = _

  def diameterOfBinaryTree(root: TreeNode): Int = {
    ans = 1
    depth(root)
    ans - 1
  }

  def depth(node: TreeNode): Int = {
    if (node == null) 0
    val L: Int = depth(node.left)
    val R: Int = depth(node.right)
    ans = Math.max(ans, L + R + 1)
    Math.max(L, R) + 1
  }

}

来源:https://stackoverflow.com/questions/60516111/for-a-binary-search-tree-i-need-to-compute-the-length-of-the-diameter-of-the-tre

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!