在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方法可以打印出反轉后的二叉樹。