forked from carpeventus/coding-interviews
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMirrorTree.java
More file actions
93 lines (80 loc) · 2.39 KB
/
MirrorTree.java
File metadata and controls
93 lines (80 loc) · 2.39 KB
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
package Chap4;
import java.util.LinkedList;
import java.util.Queue;
/**
* 操作给定的二叉树,将其变换为源二叉树的镜像。
*/
public class MirrorTree {
private class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
/**
* 递归版本
*/
public void mirrorRecur(TreeNode root) {
exchangeChildren(root);
}
private void exchangeChildren(TreeNode node) {
if (node == null) {
return;
}
if (node.left == null && node.right == null) {
return;
}
// 交换两个子结点
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
if (node.left != null) exchangeChildren(node.left);
if (node.right != null) exchangeChildren(node.right);
}
/**
* 非递归版本,层序遍历
*/
public void mirror(TreeNode root) {
if (root == null) {
return;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
// 交换两个子结点
if (node.left != null || node.right != null) {
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
}
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
}
/**
* 非递归,前序遍历
*/
public void mirror_preOrder(TreeNode root) {
LinkedList<TreeNode> stack = new LinkedList<>();
// 当前结点不为空,或者为空但有可以返回的父结点(可以进行pop操作)都可以进入循环
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
// 交换两个子结点
if (root.left != null || root.right != null) {
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
}
root = root.left;
}
if (!stack.isEmpty()) {
root = stack.pop();
root = root.right;
}
}
}
}