-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathMirror.cs
119 lines (106 loc) · 2.95 KB
/
Mirror.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/*
题目名称:
二叉树的镜像
题目描述:
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
代码结构:
class Solution
{
public TreeNode Mirror(TreeNode root)
{
// write code here
}
}
*/
using System;
using System.Collections.Generic;
namespace Mirror {
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode (int x)
{
val = x;
}
}
class Solution {
/// <summary>
/// 解法1,递归
/// 基本思路:
/// 先翻转根节点的左右子节点,然后通过递归再分别翻转左右子节点的子节点
/// </summary>
public TreeNode Mirror(TreeNode root)
{
if(root != null){
TreeNode node = root.left;
root.left = root.right;
root.right = node;
Mirror(root.left);
Mirror(root.right);
}
return root;
}
/// <summary>
/// 解法2,非递归
/// 利用栈结构遍历每一个节点,替换该节点的左右子节点
/// </summary>
public TreeNode Mirror2(TreeNode root)
{
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.Push(root);
while(stack.Count > 0){
TreeNode node = stack.Pop();
if(node != null){
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
stack.Push(node.left);
stack.Push(node.right);
}
}
return root;
}
public void Print(TreeNode root){
Queue<TreeNode> queue = new Queue<TreeNode>();
queue.Enqueue(root);
while(queue.Count > 0){
TreeNode node = queue.Dequeue();
if(node == null){
Console.Write("# ");
} else{
Console.Write(node.val + " ");
queue.Enqueue(node.left);
queue.Enqueue(node.right);
}
}
Console.WriteLine();
}
public void Test() {
TreeNode root = new TreeNode(8);
root.left = new TreeNode(6);
root.right = new TreeNode(10);
// root.left.left = new TreeNode(5);
// root.left.right = new TreeNode(7);
root.right.left = new TreeNode(9);
// root.right.right = new TreeNode(11);
// root = null;
// Print(Mirror(root));
Print(Mirror2(root));
}
}
}