From 633cb549fb21c4f45a366a973dcc30768a97a03f Mon Sep 17 00:00:00 2001 From: Javie Deng Date: Mon, 20 Mar 2023 12:36:06 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=BA0226.=E7=BF=BB=E8=BD=AC=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E6=B7=BB=E5=8A=A0=E4=BA=86C#=E8=AF=AD?= =?UTF-8?q?=E8=A8=80=E7=89=88=EF=BC=88=E5=8C=85=E5=90=AB=E9=80=92=E5=BD=92?= =?UTF-8?q?=E5=92=8C=E8=BF=AD=E4=BB=A3=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0226.翻转二叉树.md | 47 ++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md index 16a5be57..611e971a 100644 --- a/problems/0226.翻转二叉树.md +++ b/problems/0226.翻转二叉树.md @@ -914,6 +914,53 @@ impl Solution { } ``` +### C# + +```csharp +//递归 +public class Solution { + public TreeNode InvertTree(TreeNode root) { + if (root == null) return root; + + swap(root); + InvertTree(root.left); + InvertTree(root.right); + return root; + } + + public void swap(TreeNode node) { + TreeNode temp = node.left; + node.left = node.right; + node.right = temp; + } +} +``` + +```csharp +//迭代 +public class Solution { + public TreeNode InvertTree(TreeNode root) { + if (root == null) return null; + Stack stack=new Stack(); + stack.Push(root); + while(stack.Count>0) + { + TreeNode node = stack.Pop(); + swap(node); + if(node.right!=null) stack.Push(node.right); + if(node.left!=null) stack.Push(node.left); + } + return root; + } + + public void swap(TreeNode node) { + TreeNode temp = node.left; + node.left = node.right; + node.right = temp; + } +} +``` +