This question is to find the sum of the longest path of a tree in recursion. Here is my code that I have come up with.
class TreeNode<T>(var key: T){
var left: TreeNode<T>? = null
var right: TreeNode<T>? = null
}
fun maxPathSum(root: TreeNode<Int>): Int{
val leftChildPath = (root.left?.let { maxPathSum(it) } ?: Int.MIN_VALUE)
val rightChildPath = (root.right?.let { maxPathSum(it) } ?: Int.MIN_VALUE )
val maxChildPath = leftChildPath + rightChildPath
return root.key + maxChildPath
}
fun buildTree3(): TreeNode<Int>{
val one = TreeNode(1)
val two = TreeNode(2)
val three = TreeNode(3)
val four = TreeNode(4)
val five = TreeNode(5)
val eleven = TreeNode(11)
five.left = eleven
five.right = three
eleven.right = four
eleven.left = two
three.right = one
return five
}
The output I got was this.
-------Max Root to Leaf Path Sum-------
-2147483622
Not sure if it's the address of the node or not but he expected answer is 20. Thanks in advance.