Merge pull request #1968 from JavieDeng/master

为0226.翻转二叉树添加了C#语言版(包含递归和迭代)
This commit is contained in:
程序员Carl
2023-05-24 09:16:48 +08:00
committed by GitHub

View File

@ -991,6 +991,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<TreeNode> stack=new Stack<TreeNode>();
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;
}
}
```
<p align="center"> <p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank"> <a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/> <img src="../pics/网站星球宣传海报.jpg" width="1000"/>