reverse a red-black tree in csharp

To reverse a red-black tree in C#, we can traverse the tree in a postorder fashion and swap the left and right children of each node. Here's the code:

main.cs
public void Reverse()
{
    Reverse(root);
}

private void Reverse(Node node)
{
    if (node == null)
    {
        return;
    }

    Reverse(node.Left);
    Reverse(node.Right);

    // swap the left and right children of the current node
    Node temp = node.Left;
    node.Left = node.Right;
    node.Right = temp;
}
321 chars
21 lines

We start by calling the Reverse() method on the root of the tree. This method then calls a private helper method Reverse(Node node) to recursively reverse the children of each node.

At each node, we call Reverse() on the left and right children first. This ensures that all the children of the current node have already been reversed before we swap them. We then swap the left and right children using a temporary variable.

Once we've finished reversing all the nodes in the tree, the red-black tree will be fully reversed.

gistlibby LogSnag