public class Node {
String value;
List<Node> children = new ArrayList<Node>();
public Node(String value){
this.value = value;
}
public static void main(String[] args) {
Node root = new Node("A");
root.children.add(new Node("B"));
root.children.add(new Node("C"));
root.children.get(1).children.add(new Node("C1"));
root.children.get(1).children.get(0).children.add(new Node("C11"));
root.children.get(1).children.get(0).children.add(new Node("C12"));
root.children.get(1).children.add(new Node("C2"));
root.children.add(new Node("D"));
root.children.get(2).children.add(new Node("D1"));
root.children.get(2).children.add(new Node("D2"));
// 上面是初始化数据,结构是这样的:
/**
* A
* B
* C
* C1
* C11
* C12
* C2
* D
* D1
* D2
*/
System.out.println("深度优先");
print(root);
System.out.println("-----------------------");
System.out.println("广度优先");
print2(root, root, 1);
}
/**
* 深度优先
*
* @param node
* @param level
*/
static void print(Node node) {
System.out.println(node.value);
if (!node.children.isEmpty()) {
for (Node x : node.children) {
print(x);
}
}
}
/**
* 广度优先
*
* @param root
* @param node
* @param level
*/
static void print2(Node root, Node node, int level) {
if (root == node) {
System.out.println(node.value);
}
print3(root, 1, level);
if (!node.children.isEmpty()) {
for (Node x : node.children) {
print2(root, x, level += 1);
}
}
}
static void print3(Node node, int start, int level) {
List<Node> children = node.children;
if (!children.isEmpty()) {
if (start < level) {
for (Node x : children) {
print3(x, start + 1, level);
}
} else {
for (Node x : children) {
System.out.println(x.value);
}
}
}
}
}
深度优先
A
B
C
C1
C11
C12
C2
D
D1
D2
-----------------------
广度优先
A
B
C
D
C1
C2
D1
D2
C11
C12
把上面main()中的print2(xxx)换成print5(root);
/**
* 广度优先 —— 法2
*
* @param node
*/
static void print5(Node node) {
List<Node> list = node.children;
do {
for (Node x : list) {
System.out.println(x.value);
}
list = getNextLevelNode(list);
} while (list != null);
}
static List<Node> getNextLevelNode(List<Node> nodeList) {
if (!nodeList.isEmpty()) {
List<Node> list = new ArrayList<Node>();
for (Node node : nodeList) {
list.addAll(node.children);
}
return list;
}
return null;
}
-----------------------
广度优先
B
C
D
C1
C2
D1
D2
C11
C12