invert a binary tree in csharp

Here's an example implementation of a binary tree inversion algorithm using recursion in C#:

main.cs
public class TreeNode 
{
    public int val;
    public TreeNode left;
    public TreeNode right;
    
    public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null) 
    {
        this.val = val;
        this.left = left;
        this.right = right;        
    }
}

public class Solution 
{
    public TreeNode InvertTree(TreeNode root) 
    {
        if (root == null) 
        {
            return null;
        }
        
        TreeNode right = InvertTree(root.right);
        TreeNode left = InvertTree(root.left);
        
        root.left = right;
        root.right = left;
        
        return root;
    }
}
639 chars
33 lines

This function takes the root node of a binary tree and recursively inverts its left and right subtrees. The basic idea is to perform a depth-first traversal of the tree, swapping the left and right subtrees for every node encountered. Finally, the resulting inverted tree is returned.

gistlibby LogSnag