遍历一个n元树,而无需使用recurrsion [英] Traversing a n-ary tree without using recurrsion
本文介绍了遍历一个n元树,而无需使用recurrsion的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何能遍历 N
进制树不使用递归?
递归的方式:
移动(节点节点)
{
如果(节点== NULL)
返回;
对于(子节点:node.getChilds()){
遍历(子);
}
}
解决方案
您可以做到这一点不递归,没有一个堆栈。但是,你需要两个额外的指针添加到节点:
- 的父节点。所以,你可以回来的父母,如果你完成。
-
让你知道下一步采取哪一个目前的子节点。
- 对于每一个节点,处理所有的孩子们。
- 如果一个孩子的处理,你检查是否有下一个孩子并处理(更新电流)。
- 如果所有的孩子进行处理,回到父母。
- 如果该节点为NULL,退出。
使用伪$ C C $这个样子:
移动(节点node){
而(节点){
如果(与于节点GT;电流I = MAX_CHILD){
节点preV =节点;
如果(与于节点GT;孩子[&于节点GT;当前]){
节点= - 于节点GT;孩子[&于节点GT;当前]。
}
preV->当前++;
} 其他 {
//做你的事与节点。
于节点>电流= 0; //重置柜台旁边穿越。
节点= - 于节点GT;父母;
}
}
}
How can I traverse an n
-ary tree without using recursion?
Recursive way:
traverse(Node node)
{
if(node == null)
return;
for(Node child : node.getChilds()) {
traverse(child);
}
}
解决方案
You can do this without recursion and without a stack. But you need to add two extra pointers to the node:
- The parent node. So you can come back to the parent if you are finished.
The current child node so you know which one to take next.
- For each node, you handle all the kids.
- If a kid is handled, you check if there is a next kid and handle that (updating the current).
- If all kids are handled, go back to the parent.
- If the node is NULL, quit.
With pseudocode this looks like:
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;
}
}
}
这篇关于遍历一个n元树,而无需使用recurrsion的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文