在C#中,可以通过递归的方式实现二叉树的镜像反转。具体步骤如下:
以下是一个示例实现:
using System;
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 BinaryTreeMirror
{
public void MirrorTree(TreeNode root)
{
if (root == null) return;
// 交换当前节点的左右子节点
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
// 递归调用该函数对左右子节点进行镜像反转
MirrorTree(root.left);
MirrorTree(root.right);
}
public void PrintTree(TreeNode root)
{
if (root == null) return;
Console.WriteLine(root.val);
PrintTree(root.left);
PrintTree(root.right);
}
}
class Program
{
static void Main()
{
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
BinaryTreeMirror treeMirror = new BinaryTreeMirror();
Console.WriteLine("Original Tree:");
treeMirror.PrintTree(root);
treeMirror.MirrorTree(root);
Console.WriteLine("Mirrored Tree:");
treeMirror.PrintTree(root);
}
}
在上面的示例中,我们首先构建了一个简单的二叉树,并实例化了一个BinaryTreeMirror类,其中包含了一个MirrorTree方法用于实现二叉树的镜像反转操作。通过调用MirrorTree方法,可以实现对二叉树的镜像反转,最后通过PrintTree方法可以打印出反转后的二叉树。