0

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));

}
user3311298
  • 335
  • 5
  • 12
  • 1
    To me, this question could be distilled down to "when should I use 'out' versus 'ref'". Unless I'm missing something, recursion, binary trees, and the code examples won't affect the answer. "out" versus "ref" is discussed here: http://stackoverflow.com/questions/1516876/when-to-use-ref-vs-out – Jamey Dec 04 '16 at 03:59
  • I read that article before posting this question. I have some reasons to use out and some to use ref. What I am struggling with what takes preference over other. I read somewhere "always use out unless you really need to use ref". Here I feel like ref is a better fit but because I can get away with using out too, the sentence " "always use out unless you really need to use ref". is really confusing me. – user3311298 Dec 04 '16 at 13:49

0 Answers0