forked from Wang-Jun-Chao/coding-interviews
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Test19.java
120 lines (113 loc) · 3.22 KB
/
Test19.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
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
/**
* Author: 王俊超
* Date: 2015-04-23
* Time: 20:49
* Declaration: All Rights Reserved !!!
*/
public class Test19 {
/**
* 二叉树的树结点
*/
public static class BinaryTreeNode {
int value;
BinaryTreeNode left;
BinaryTreeNode right;
}
/**
* 请完成一个函数,输入…个二叉树,该函数输出它的镜像
*
* @param node 二叉树的根结点
*/
public static void mirror(BinaryTreeNode node) {
// 如果当前结点不为空则进行操作
if (node != null) {
// 下面是交换结点左右两个子树
BinaryTreeNode tmp = node.left;
node.left = node.right;
node.right = tmp;
// 对结点的左右两个子树进行处理
mirror(node.left);
mirror(node.right);
}
}
public static void printTree(BinaryTreeNode node) {
if (node != null) {
printTree(node.left);
System.out.print(node.value + " ");
printTree(node.right);
}
}
public static void main(String[] args) {
// 8
// / \
// 6 10
// / \ / \
// 5 7 9 11
BinaryTreeNode root = new BinaryTreeNode();
root.value = 8;
root.left = new BinaryTreeNode();
root.left.value = 6;
root.left.left = new BinaryTreeNode();
root.left.left.value = 5;
root.left.right = new BinaryTreeNode();
root.left.right.value = 7;
root.right = new BinaryTreeNode();
root.right.value = 10;
root.right.left = new BinaryTreeNode();
root.right.left.value = 9;
root.right.right = new BinaryTreeNode();
root.right.right.value = 11;
printTree(root);
System.out.println();
mirror(root);
printTree(root);
// 1
// /
// 3
// /
// 5
// /
// 7
// /
// 9
BinaryTreeNode root2 = new BinaryTreeNode();
root2.value = 1;
root2.left = new BinaryTreeNode();
root2.left.value = 3;
root2.left.left = new BinaryTreeNode();
root2.left.left.value = 5;
root2.left.left.left = new BinaryTreeNode();
root2.left.left.left.value = 7;
root2.left.left.left.left = new BinaryTreeNode();
root2.left.left.left.left.value = 9;
System.out.println("\n");
printTree(root2);
System.out.println();
mirror(root2);
printTree(root2);
// 0
// \
// 2
// \
// 4
// \
// 6
// \
// 8
BinaryTreeNode root3 = new BinaryTreeNode();
root3.value = 0;
root3.right = new BinaryTreeNode();
root3.right.value = 2;
root3.right.right = new BinaryTreeNode();
root3.right.right.value = 4;
root3.right.right.right = new BinaryTreeNode();
root3.right.right.right.value = 6;
root3.right.right.right.right = new BinaryTreeNode();
root3.right.right.right.right.value = 8;
System.out.println("\n");
printTree(root3);
System.out.println();
mirror(root3);
printTree(root3);
}
}