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:
I suggest the following:
public static TreeAttr calcTreeDiameter(Node root) {
if (root == null)
return new TreeAttr(0, 0);
TreeAttr leftAttr = calcTreeDiameter(root.getLeft());
TreeAttr rightAttr = calcTreeDiameter(root.getRight());
int maxDepth = Math.max(leftAttr.depth, rightAttr.depth);
int maxDiam = Math.max(leftAttr.diameter, rightAttr.diameter);
maxDiam = Math.max(maxDiam, leftAttr.depth + rightAttr.depth + 1);
return new TreeAttr(maxDiam, maxDepth + 1);
}
The TreeAttr is a simple structure containing the diameter and depth of a subtree. Both should be passed in the recursion, since the optimum may either come from one of the subtrees, or from the concatenation of the longest paths.