就是按照正常顺序把tree打出来,假设有个tree是
1
/ \
2 3
/ \ / \
4 5 6 7
打印出来就是 1,2,3,4,5,6,7;
这个就是宽度优先
package org.iaiai.suanfa;
import java.util.LinkedList;
/**
*
* <p>
* Title: Node.java
* </p>
* <p>
* Http: iaiai.iteye.com
* </p>
* <p>
* Create time: 2011-8-5
* </p>
*
* @author 丸子
* @version 0.0.1
*/
public class Node {
public int level = 0;
public String path = " ";
public LinkedList<Node> children = new LinkedList<Node>();
public String value = " ";
public String name = " ";
/**
*
* @param val
* 第几级
* @param name
* 名子
* @param parent
* 父级
*/
public Node(String val, String name, Node parent) {
this.value = val;
this.name = name;
if (parent != null) {
parent.addChild(this);
path = parent.path + " " + name;
} else
path = name;
}
public void addChild(Node child) {
children.add(child);
}
}
package org.iaiai.suanfa;
import java.util.LinkedList;
import java.util.List;
/**
*
* <p>
* Title: Main.java
* </p>
* <p>
* Http: iaiai.iteye.com
* </p>
* <p>
* Create time: 2011-8-5
* </p>
*
* @author 丸子
* @version 0.0.1
*/
public class Main {
public static void main(String[] args) throws Exception {
int n = 3;
String[] str = { "1", "2", "3" };
Node A = new Node("1", "A", null);
Node B = new Node("2", "B", A);
Node C = new Node("2", "C", A);
new Node("3", "B1", B);
new Node("x", "B2", B); // x为不显示
new Node("x", "B3", B);
new Node("3", "B4", B);
new Node("x", "C1", C);
new Node("3", "C2", C);
new Node("x", "C3", C);
new Node("3", "C4", C);
new Node("3", "C5", C);
List<Node> queue = new LinkedList<Node>();
if (A.value.equals(str[A.level]))
queue.add(A);
while (queue.size() > 0) {
Node cur = queue.remove(0);
LinkedList<Node> children = cur.children;
for (int i = 0; i < children.size(); i++) {
if (children.get(i).value.equals(str[cur.level + 1])) {
if (cur.level + 1 == n - 1)
System.out.println(children.get(i).path);
else {
children.get(i).level = cur.level + 1;
queue.add(children.get(i));
}
}
}
}
}
}
输出:
[quote]
A B B1
A B B4
A C C2
A C C4
A C C5
[/quote]