I am writing recursive method to get diameter of a binary tree.1st method uses out and 2nd method uses ref.I am not sure which of the two is better. Here are the reasons I could think of to use ref or out.
reasons to use ref-
1) Do not need the height back eventually, I am returning back just the diameter
reasons to use out-
1) Height does not need to be initialized.
2) I do not need data to be passed bidirectional
3) I do not need to copy the initial value because method is not dependent on it.
If I would use ref then the reference would be copied.
USING OUT -
public int GetDiameterMoreEfficient(Node root)
{
int height;
return GetDiameterMoreEfficient(root, out height);
}
public int GetDiameterMoreEfficient(Node root, out int height)
{
if (root == null) {height = 0; return 0;}
int lHeight;
int rHeight;
var diameterOfLeft = GetDiameterMoreEfficient(root.Left, out lHeight);
var diameterOfRight = GetDiameterMoreEfficient(root.Right, out rHeight);
height = (lHeight > rHeight ? lHeight : rHeight) + 1;
return Math.Max((lHeight + rHeight + 1), Math.Max(diameterOfLeft, diameterOfRight));
}
USING REF-
public int GetDiameterMoreEfficient(Node root)
{
int height = 0;
return GetDiameterMoreEfficient(root, ref height);
}
public int GetDiameterMoreEfficient(Node root, ref int height)
{
if (root == null) { height = 0; return 0; }
int lHeight = 0;
int rHeight = 0;
var diameterOfLeft = GetDiameterMoreEfficient(root.Left, ref lHeight);
var diameterOfRight = GetDiameterMoreEfficient(root.Right, ref rHeight);
height = (lHeight > rHeight ? lHeight : rHeight) + 1;
return Math.Max((lHeight + rHeight + 1), Math.Max(diameterOfLeft, diameterOfRight));
}