c - Traversing a tree using linked list structure -
i have struct node contains next , child.
struct node{ node *parent; node *next; node *child; }
the following picture shows structure of tree.
how write function traverse tree? without recursion ?
i have pseudo code in mind not sure if correct or no, because each node can have child , need search using child too
while ( root !=null) { root = root->next; }
i visit nodes.
i guess tree this:
-> grandma -> dad -> me -> sister -> niece -> brother -> uncle -> cousin
where indentation means level of ancestry. recursive function simple:
void traverse_rec(const node *node) { if (node) { process(node); traverse_rec(node->child); traverse_rec(node->next); } }
this can rewritten loop. if current node has child, that's next node visit. otherwise, want visit sibling. node may not have sibling. because have link parent node (and root node's parent should ´null), can backtrack tree until find sibling follow or until node null
.
void traverse2(const node *node) { while (node) { puts(node->name); if (node->child) { node = node->child; } else { while (node && node->next == null) { node = node->parent; } if (node) node = node->next; } } }
this more complicated recursive function, can transformed iterator-like code, next node:
const node *next(const node *node) { if (node == null) return null; if (node->child) return node->child; while (node && node->next == null) { node = node->parent; } if (node) return node->next; return null; }
with "iterator", can write code like:
for (const node *p = root; p; p = next(p)) { puts(p->name); }
Comments
Post a Comment