根據the wikipedia article about depth-first search中的解釋,我認爲二叉樹上的DFS與先前遍歷的根 - 左 - 右(我是對嗎?)完全相同。如何在java中的二叉樹上實現深度優先搜索(DFS)?
但是我只是做了一點搜索並得到了這段代碼,其作者聲稱DFS需要一棵樹來記錄節點是否曾經訪問過(或者我們是否需要這個在圖的情況下?)。
// copyright belongs to the original author
public void dfs() {
// DFS uses Stack data structure
Stack stack = new Stack();
stack.push(this.rootNode);
rootNode.visited=true;
printNode(rootNode);
while(!stack.isEmpty()) {
Node node = (Node)s.peek();
Node child = getUnvisitedChildNode(n);
if(child != null) {
child.visited = true;
printNode(child);
s.push(child);
}
else {
s.pop();
}
}
// Clear visited property of nodes
clearNodes();
}
有人能解釋這個嗎?
您可以在此鏈接(http://en.wikipedia.org/wiki/Depth-first_search)右側檢查圖像嗎? – Accessdenier 2013-03-06 01:47:23