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:
You should use the height of the tree to calculate the diameter. Make a getHeight() function which will take the root of the tree as argument and return the height of the tree. Using this value and with the help of recursion we can calculate the diameter of the tree. Here is the code for it.....
Function for calculating the diameter :-
public static int getDiameter(BinaryTreeNode root) {
if (root == null)
return 0;
int rootDiameter = findHeight(root.getLeft()) + findHeight(root.getRight()) + 1;
int leftDiameter = getDiameter(root.getLeft());
int rightDiameter = getDiameter(root.getRight());
return Math.max(rootDiameter, Math.max(leftDiameter, rightDiameter));
}
Function for calculating the height of tree:-
public static int findHeight(BinaryTreeNode node) {
if(node == null)
return 0;
else {
return 1+Math.max(findHeight(node.left), findHeight(node.right));
}
}