Skip to content

Commit 9d60747

Browse files
committed
common/rbtree: Add tree traversal and get root routines
The commit adds two routines: - tree traversal that applies user-provided handler function for each node - get root of a tree The routines will be used in the further commits Signed-off-by: Dmitry Gladkov <[email protected]>
1 parent a6e33da commit 9d60747

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

include/rbtree.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,5 +95,12 @@ RbtIterator rbtFindLeftmost(RbtHandle h, void *key,
9595
RbtIterator rbtFind(RbtHandle h, void *key);
9696
// returns iterator associated with key
9797

98+
void rbtTraversal(RbtHandle h, RbtIterator it, void *handler_arg,
99+
void(*handler)(void *arg, RbtIterator it));
100+
// tree traversal that visits (applies handler()) each node in the tree data
101+
// strucutre exactly once.
102+
103+
void *rbtRoot(RbtHandle h);
104+
// returns the root of the tree
98105

99106
#endif /* RBTREE_H_ */

src/rbtree.c

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -434,3 +434,24 @@ void *rbtFind(RbtHandle h, void *key) {
434434
}
435435
return NULL;
436436
}
437+
438+
void rbtTraversal(RbtHandle h, RbtIterator it, void *handler_arg,
439+
void(*handler)(void *arg, RbtIterator it)) {
440+
RbtType *rbt = h;
441+
NodeType *root = it;
442+
443+
// apply handler for:
444+
// -o the root of the tree/subtree
445+
handler(handler_arg, it);
446+
// - the left subtree
447+
if (root->left != SENTINEL)
448+
rbtTraversal(h, root->left, handler_arg, handler);
449+
// - the right subtree
450+
if (root->right != SENTINEL)
451+
rbtTraversal(h, root->right, handler_arg, handler);
452+
}
453+
454+
void *rbtRoot(RbtHandle h) {
455+
RbtType *rbt = h;
456+
return rbt->root;
457+
}

0 commit comments

Comments
 (0)