ako*_*ako 19 algorithm tree-traversal
如何在n
不使用递归的情况下遍历一棵树?
递归方式:
traverse(Node node)
{
if(node == null)
return;
for(Node child : node.getChilds()) {
traverse(child);
}
}
Run Code Online (Sandbox Code Playgroud)
BiG*_*YaN 22
你在做什么本质上是树的DFS.您可以使用堆栈消除递归:
traverse(Node node) {
if (node==NULL)
return;
stack<Node> stk;
stk.push(node);
while (!stk.empty()) {
Node top = stk.pop();
for (Node child in top.getChildren()) {
stk.push(child);
}
process(top);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您希望BFS使用队列:
traverse(Node node) {
if (node==NULL)
return;
queue<Node> que;
que.addRear(node);
while (!que.empty()) {
Node front = que.deleteFront();
for (Node child in front.getChildren()) {
que.addRear(child);
}
process(front);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您想要其他方式遍历,您将必须遵循相同的方法,尽管使用不同的数据结构来存储节点.可能是优先级队列(如果要在每个节点上评估函数,然后根据该值处理节点).
Too*_*the 10
你可以在没有递归和没有堆栈的情况下做到这一点.但是您需要向节点添加两个额外的指针:
当前子节点,以便您知道接下来要采用哪个节点.
使用伪代码,它看起来像:
traverse(Node node) {
while (node) {
if (node->current <= MAX_CHILD) {
Node prev = node;
if (node->child[node->current]) {
node = node->child[node->current];
}
prev->current++;
} else {
// Do your thing with the node.
node->current = 0; // Reset counter for next traversal.
node = node->parent;
}
}
}
Run Code Online (Sandbox Code Playgroud)
没有给出语言,所以在伪伪代码中:
traverse(Node node)
{
List<Node> nodes = [node];
while (nodes.notEmpty) {
Node n = nodes.shift();
for (Node child in n.getChildren()) {
nodes.add(child);
}
// do stuff with n, maybe
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,这是一个广度优先的遍历,而不是问题中给出的深度优先遍历.您应该能够通过列表中pop
的最后一项nodes
而不是shift
第一项来进行深度优先遍历.