-
Notifications
You must be signed in to change notification settings - Fork 32
/
BinaryTreeTraverseSample.java
126 lines (104 loc) · 3.02 KB
/
BinaryTreeTraverseSample.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
121
122
123
124
125
import java.util.LinkedList;
import java.util.Queue;
/**
* 此类演示了二叉树的创建和遍历
*/
public class BinaryTreeTraverseSample{
public static void main(String[] args) {
TreeNode tree = new TreeNode(1);
// 填充数据
TreeNode node2 = new TreeNode(2);
TreeNode node3 = new TreeNode(3);
TreeNode node5 = new TreeNode(5);
TreeNode node6 = new TreeNode(6);
TreeNode node7 = new TreeNode(7);
TreeNode node10 = new TreeNode(10);
tree.lChild = node2;
tree.rChild = node3;
node2.rChild = node5;
node3.lChild = node6;
node3.rChild = node7;
node5.lChild = node10;
// 层序遍历输出
levelTraverse(tree);
System.out.println("---------------------------------------------------------");
// 前序遍历输出
preOrderTraverse(tree);
System.out.println("---------------------------------------------------------");
// 中序遍历输出
inOrderTraverse(tree);
System.out.println("---------------------------------------------------------");
// 后序遍历输出
postOrderTraverse(tree);
}
/**
* 层序遍历输出
*
* 思路是利用队列FIFO特性
* 1. 入队根结点
* 2. 根结点出队,入队左子结点和右子结点
*/
private static void levelTraverse(TreeNode tree){
if(tree == null) return;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(tree);
TreeNode node;
while (!queue.isEmpty()) {
node = queue.poll();
System.out.println("Node is " + node.data);
if(node.lChild!=null){
queue.offer(node.lChild);
}
if(node.rChild!=null){
queue.offer(node.rChild);
}
}
}
/**
* 前序遍历输出
* 先根结点
*/
private static void preOrderTraverse(TreeNode tree){
if (tree == null) {
return;
}
System.out.println("Node is " + tree.data);
preOrderTraverse(tree.lChild);
preOrderTraverse(tree.rChild);
}
/**
* 中序遍历输出
* 先左孩子,再根结点
*/
private static void inOrderTraverse(TreeNode tree){
if (tree == null) {
return;
}
inOrderTraverse(tree.lChild);
System.out.println("Node is " + tree.data);
inOrderTraverse(tree.rChild);
}
/**
* 后序遍历输出
* 先左孩子,再右孩子,最后再根结点
*/
private static void postOrderTraverse(TreeNode tree){
if (tree == null) {
return;
}
postOrderTraverse(tree.lChild);
postOrderTraverse(tree.rChild);
System.out.println("Node is " + tree.data);
}
}
/**
* 链式存储的结点数据结构
*/
class TreeNode{
Integer data;
TreeNode lChild;
TreeNode rChild;
public TreeNode(Integer data){
this.data = data;
}
}