使用ref或out作为递归方法

时间:2016-12-04 03:18:24

标签: c# c#-4.0 recursion

我正在编写递归方法来获取二叉树的直径.1方法使用out和第二种方法使用ref。我不确定哪两个更好。 以下是我可以考虑使用ref或out的原因。

使用ref的理由 -

  1) Do not need the height back eventually, I am returning back just the diameter

使用的理由 -

  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.

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

}

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

}

0 个答案:

没有答案