树是一种在计算机科学中十分重要的数据结构,二叉树作为一种特殊的树,其性质相较于普通的树而言又有很多的不同。

本文提供了一种由 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
public class BinaryTree {

private class Node {

private Node left;
private Node right;
private Object value;

public Node(Object value) {
this.value = value;
}

}

public Node root = null;

/*
* A
* B C
* D E F G
*/

public void createBinaryTree() {
root = new Node("A");
Node B = new Node("B");
Node C = new Node("C");
Node D = new Node("D");
Node E = new Node("E");
Node F = new Node("F");
Node G = new Node("G");
root.left = B;
root.right = C;
B.left = D;
B.right = E;
C.left = F;
C.right = G;
}

public boolean isEmpty() {
return root == null;
}

// 先序遍历
public void preTraverse(Node node) {
if (null != node) {
System.out.println(node.value);
preTraverse(node.left);
preTraverse(node.right);
}
}

// 中序遍历
public void midTraverse(Node node) {
if (null != node) {
midTraverse(node.left);
System.out.println(node.value);
midTraverse(node.right);
}
}

// 后序遍历
public void afterTraverse(Node node) {
if (null != node) {
afterTraverse(node.left);
afterTraverse(node.right);
System.out.println(node.value);
}
}

public static void main(String[] args) {
BinaryTree b = new BinaryTree();
b.createBinaryTree();
b.preTraverse(b.root);
System.out.println("===========先序遍历=============");
b.midTraverse(b.root);
System.out.println("===========中序遍历=============");
b.afterTraverse(b.root);
System.out.println("===========后序遍历=============");
}

}