Domanda

I'm preparing for an interview, so as an exercise I've implemented algorithm to check if a binary tree is BST.

    public static bool CheckBST(this Node root)
    {
        if (root == null) throw new ArgumentException("root");
        Node previous = null;
        foreach (var node in GetNodes(root))
        {
            if (previous != null && node.value <= previous.value)
            {
                return false;
            }
            previous = node;
        }
        return true;
    }

    private static IEnumerable<Node> GetNodes(Node root)
    {
        if (root.left != null)
        {
            foreach (var node in GetNodes(root.left))
            {
                yield return node;
            }
        }
        yield return root;
        if (root.right != null)
        {
            foreach (var node in GetNodes(root.right))
            {
                yield return node;
            }
        }
    }  

Can get rid of foreach loops(still using recursion and yield)?

È stato utile?

Soluzione

No, unfortunately, there is no way to achieve this.
There is no such thing as yield return many GetNodes(...); and mixing yield return and normal return is also not allowed.

However, you can achieve the desired result (deferred execution) using LINQ:

private static IEnumerable<Node> GetNodes(Node root)
{
    var result = Enumerable.Empty<Node>();

    if (root.left != null)
        result = result.Concat(GetNodes(root.left));

    result = result.Concat(new [] { root });

    if (root.right != null)
        result = result.Concat(GetNodes(root.right));

    return result;
}

Whether this is better than what you currently have is debatable.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top