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)?
No, unfortunately, there is no way to achieve this.
There is no such thing as
yield return many GetNodes(...);and mixingyield returnand normalreturnis also not allowed.However, you can achieve the desired result (deferred execution) using LINQ:
Whether this is better than what you currently have is debatable.