I am working on an assignment right now, and I have found a solution to the problem online (which looks ridiculously simple but works like magic)
I am still having some trouble comprehending how recursion exactly works and I actually want to learn.
Could someone help me with understanding this logic please?
The question is to find the longest path from root node to a leaf node. (Basically find the height of the tree ?).
The function is as follows:
public static int findPath(TreeNode<Integer> node)
{
if (node == null)
return 0;
else
{
return 1 + Math.max(findPath(node.left), findPath(node.right) );
}
}
and this is my treeNode class definition:
public class TreeNode<T> {
T v;
TreeNode<T> left;
TreeNode<T> right;
TreeNode(T value) //initialize treeNode with treeNode(value)
{
v = value;
left = null;
right = null;
}
}