mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
为0226.翻转二叉树添加了C#语言版(包含递归和迭代)
This commit is contained in:
@ -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<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"/>
|
||||||
|
Reference in New Issue
Block a user