Repository navigation
Expand file tree
/
Copy pathTreeTraversalsExample.java
More file actions
62 lines (54 loc) · 1.59 KB
/
Copy pathTreeTraversalsExample.java
File metadata and controls
62 lines (54 loc) · 1.59 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
package ch14;
public class TreeTraversalsExample {
static class TNode {
char val;
TNode left;
TNode right;
TNode(char val) {
this.val = val;
}
TNode(char val, TNode left, TNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public static void preorder(TNode node) {
if (node == null) return;
System.out.printf("%c ", node.val);
preorder(node.left);
preorder(node.right);
}
public static void inorder(TNode node) {
if (node == null) return;
inorder(node.left);
System.out.printf("%c ", node.val);
inorder(node.right);
}
public static void postorder(TNode node) {
if (node == null) return;
postorder(node.left);
postorder(node.right);
System.out.printf("%c ", node.val);
}
public static void main(String[] args) {
// 그림 14-26 예제 트리 생성
TNode root =
new TNode(
'F',
new TNode(
'B',
new TNode('A'),
new TNode('D', new TNode('C'), new TNode('E'))),
new TNode('G', null, new TNode('I', new TNode('H'), null)));
// 전위 순회
preorder(root);
System.out.println();
// 중위 순회
inorder(root);
System.out.println();
// 후위 순회
postorder(root);
System.out.println();
}
}