【发布时间】:2013-03-06 01:37:19
【问题描述】:
根据the wikipedia article about depth-first search 中的解释,我认为二叉树上的 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();
}
谁能解释一下?
【问题讨论】: