C# || How To Invert Binary Tree Using C#

Print Friendly, PDF & Email

The following is a module with functions which demonstrates how to invert a binary tree using C#.

1. Invert Tree – Problem Statement

Given the root of a binary tree, invert the tree, and return its root.

Example 1:

Example 1

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

Example 2:

Example 2

Input: root = [2,1,3]
Output: [2,3,1]

Example 3:

Input: root = []
Output: []

2. Invert Tree – Solution

The following is a solution which demonstrates how to invert a binary tree.

An inverted Binary Tree is simply a Binary Tree whose left and right children are swapped.

This solution:

  • Traverses the left subtree
  • Traverses the right subtree
  • When both trees have been traversed, swap left and right child subtrees

The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:


Was this article helpful?
👍 YesNo

Leave a Reply