问题
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