尝试将递归JavaScript方法移植到C#,这种方法有意义吗?

时间:2013-01-31 00:41:57

标签: c# javascript recursion

JavaScript中的方法是:

findNode: function(root, w, h) {
    if (root.used)
        return this.findNode(root.right, w, h) || this.findNode(root.down, w, h);
    else if ((w <= root.w) && (h <= root.h))
        return root;
    else
        return null;
}

这条线特别适用于C#

return this.findNode(root.right, w, h) || this.findNode(root.down, w, h);

这是我试图翻译它,但我可以使用第二个意见来确定这是否会起作用或打破算法。有没有更好的方法让我失踪?

private Node FindNode(Node node, Block block)
{
    Node n;
    if (node.used) // recursive case
    {

        // is this a good translation of the JavaScript one-liner?

        n = FindNode(node.right, block);
        if (n != null)
        {
            return n;
        }
        else
        {
            return FindNode(node.down, block);
        }
    }
    else if ((block.width <= node.width) && (block.height <= node.height)) // Base case
    {
        return node;
    }
    else
    {
        return null;
    }
}

Here is the original algorithm I'm working off of.

1 个答案:

答案 0 :(得分:2)

n = FindNode(node.right, block);
return n ?? FindNode(node.down, block);  

将是我唯一的改变