I have this code to find the diameter of the binary tree. Diameter of a binary tree: The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two leaves in the tree.
I am trying to understand the below code and recursion in general. I am trying to dry run with this simple tree. I understand when root is 20 height will become 1 (Max(0,0)+1) and then returning the Math.Max(0+0+1, Max(0,0)). My understanding here is it will set ldiameter to 1 with this return value while root = 10. Is this correct? and at this point lh gets changed to 1. How does it change to 1? Also, if you can help me dry run this simple tree step by step that will be really helpful.
10
/ \
20 30
public int FindDiameter_util(Node root, ref int height)
{
/* lh --> Height of left subtree
rh --> Height of right subtree */
int lh = 0, rh = 0;
/* ldiameter --> diameter of left subtree
rdiameter --> Diameter of right subtree */
int ldiameter = 0, rdiameter = 0;
if (root == null)
{
height = 0;
return 0; /* diameter is also 0 */
}
/* Get the heights of left and right subtrees in lh and rh
And store the returned values in ldiameter and ldiameter */
ldiameter = FindDiameter_util(root.left, ref lh);
rdiameter = FindDiameter_util(root.right, ref rh);
/* Height of current node is max of heights of left and
right subtrees plus 1*/
height = Math.Max(lh, rh) + 1;
return Math.Max(lh + rh + 1, Math.Max(ldiameter, rdiameter));
}
refs. Turn this into a method that returns an immutable struct that consists of two integers with names Height and Diameter. Second, the fact that you have to have comments that explain the variable names means that they are named badly. They should beleftDiameter,leftHeight, and so on. Third, write the algorithm so that every variable is written only once. When you have done that the code will be much easier to understand.