-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathJz18.java
More file actions
125 lines (104 loc) · 2.73 KB
/
Jz18.java
File metadata and controls
125 lines (104 loc) · 2.73 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
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
120
121
122
123
124
125
package com.cpucode.java.simple;
import java.util.*;
/**
* 题目描述
* 操作给定的二叉树,将其变换为源二叉树的镜像。
* 输入描述:
* 二叉树的镜像定义:源二叉树
* 8
* / \
* 6 10
* / \ / \
* 5 7 9 11
* 镜像二叉树
* 8
* / \
* 10 6
* / \ / \
* 11 9 7 5
*
* @author : cpucode
* @Date : 2021/1/20
* @Time : 13:28
* @Github : https://github.com/CPU-Code
* @CSDN : https://blog.csdn.net/qq_44226094
*/
public class Jz18 {
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public class test1 {
public void Mirror(TreeNode root) {
// 空树
if (root == null) {
return;
}
// 左右均为空
if (root.left == null && root.right == null) {
return;
}
// 用来遍历的栈
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
TreeNode curNode;
TreeNode tempNode;
// 深度优先
while (!stack.isEmpty()) {
curNode = stack.pop();
if(curNode == null) {
continue;
}
if(curNode.left == null && curNode.right==null) {
continue;
}
// 交换
tempNode = curNode.left;
curNode.left = curNode.right;
curNode.right = tempNode;
stack.push(curNode.left);
stack.push(curNode.right);
}
}
}
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class test2 {
public void Mirror(TreeNode root) {
// 空树
if(root == null){
return;
}
// 左右均为空
if (root.left == null && root.right == null) {
return;
}
LinkedList<TreeNode> q = new LinkedList<>();
q.add(root);
while(!q.isEmpty()){
TreeNode curr = q.poll();
TreeNode t = curr.left;
curr.left = curr.right;
curr.right = t;
if(curr.left != null){
q.add(curr.left);
}
if(curr.right != null) {
q.add(curr.right);
}
}
}
}
}