對於樹形結構主要有兩種遍歷方式:深度優先遍歷和廣度優先遍歷。

我們使用下邊的節點類來表示樹形結構(多叉樹)。

public class Node {

private String value;

private List children;

public Node(String value, List children) {

this。value = value;

this。children = children;

}

public Node() {

}

public String value() {

return this。value;

}

public void setValue(String value) {

this。value = value;

}

public void addChild(Node node) {

if (node == null) {

return;

}

this。children。add(node);

}

public List getChildren() {

return this。children;

}

}

一個簡單的樹結構圖

樹的深度優先遍歷、廣度優先遍歷

樹的深度優先遍歷、廣度優先遍歷

一、深度優先遍歷

深度優先遍歷指的是,從樹的根節點開始,先遍歷左子樹,然後遍歷右子樹。

我們藉助棧結構來實現深度優先遍歷。上圖的深度優先遍歷結果為:ABDECFG

程式碼如下:

Stack stack = new Stack();

List result = new ArrayList();

stack。push(root);

while (!stack。isEmpty()) {

Node top = stack。pop();

result。add(top);

List children = top。getChildren();

if (children != null && children。size() > 0) {

for (int i = children。size() - 1; i >= 0; i——) {

stack。push(children。get(i));

}

}

}

二、廣度優先遍歷

從根節點開始,沿著樹的寬度依次遍歷樹的每個節點。

我們藉助佇列結構來實現樹的廣度優先遍歷。上圖的遍歷結果為:ABCDEFG

程式碼如下:

Queue queue = new LinkedBlockingQueue();

List result = new ArrayList();

queue。add(root);

while (!queue。isEmpty()) {

Node first = queue。poll();

result。add(first);

List children = first。getChildren();

if (children != null && children。size() > 0) {

for (int i = 0; i < children。size(); i++) {

queue。add(children。get(i));

}

}

}

原始碼地址