ura*_*ray 11 c tree recursion traversal data-structures
如何在没有C(无C++)递归的情况下有效地遍历树的每个节点?
假设我有该树的以下节点结构:
struct Node
{
struct Node* next; /* sibling node linked list */
struct Node* parent; /* parent of current node */
struct Node* child; /* first child node */
}
Run Code Online (Sandbox Code Playgroud)
Nodestruct 的成员来存储其他信息.zeb*_*h49 20
如果您不想存储任何内容,并且可以使用深度优先搜索:
process = TRUE;
while(pNode != null) {
if(process) {
//stuff
}
if(pNode->child != null && process) {
pNode = pNode->child;
process = true;
} else if(pNode->next != null) {
pNode = pNode->next;
process = true;
} else {
pNode = pNode->parent;
process = false;
}
}
Run Code Online (Sandbox Code Playgroud)
将遍历树; process是为了防止它在返回时重新命中父节点.
通常,您将使用自己的堆栈数据结构来存储节点列表(如果您想要进行级别订单遍历,则使用队列).
首先将任何给定的起始节点推入堆栈.然后进入主循环,直到堆栈为空.从堆栈中弹出每个节点后,如果不为空,则推送其下一个节点和子节点.