-
Notifications
You must be signed in to change notification settings - Fork 148
/
MirrorRecursively19.java
56 lines (49 loc) · 1.15 KB
/
MirrorRecursively19.java
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
package com.so;
import java.util.Stack;
import com.so.Common.TreeNode;
/**
* 第19题
* 输入一个二叉树,输出它的镜像
*
* @author qgl
* @date 2017/08/10
*/
public class MirrorRecursively19 {
/**
* 解法一:递归
* @param root
*/
public void Mirror(TreeNode root) {
if (root == null) {
return;
}
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
Mirror(root.left);
Mirror(root.right);
}
/**
* 解法二:非递归,利用栈
* @param root
* @return
*/
public void Mirror2(TreeNode root) {
if (root == null) {
return ;
}
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
// 交换左右子节点
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
stack.push(root);
root = root.left;
}
root = stack.pop();
root = root.right;
}
}
}