I am trying to find the diameter of a binary tree (Path length between any two nodes in the tree containing maximum number of nodes.) in java.
my code snippet:
Algo takes O(n). Calculates height and path at the same time.
public static int findLongestPath(TreeNode root)
{
// longest path = max (h1 + h2 + 2, longestpath(left), longestpath(right);
int[] treeInfo = longestPathHelper(root);
return treeInfo[0];
}
private static int[] longestPathHelper(TreeNode root)
{
int[] retVal = new int[2];
if (root == null)
{
//height and longest path are 0
retVal[0] = 0;
retVal[1] = 0;
}
int[] leftInfo = longestPathHelper(root.getLeft());
int[] rightInfo = longestPathHelper(root.getRight());
retVal[0] = Math.max(leftInfo[1] + rightInfo[1] + 2, Math.max(leftInfo[0], rightInfo[0]));
retVal[1] = Math.max(leftInfo[1], rightInfo[1]) + 1;
return retVal;
}