Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top