From 9d607478438596365100e0f2aaf8138ce17deb99 Mon Sep 17 00:00:00 2001 From: Dmitry Gladkov Date: Mon, 10 Sep 2018 13:49:50 +0300 Subject: [PATCH] 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 --- include/rbtree.h | 7 +++++++ src/rbtree.c | 21 +++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/include/rbtree.h b/include/rbtree.h index 34ff3dbe883..a0434b71752 100644 --- a/include/rbtree.h +++ b/include/rbtree.h @@ -95,5 +95,12 @@ RbtIterator rbtFindLeftmost(RbtHandle h, void *key, RbtIterator rbtFind(RbtHandle h, void *key); // returns iterator associated with key +void rbtTraversal(RbtHandle h, RbtIterator it, void *handler_arg, + void(*handler)(void *arg, RbtIterator it)); +// tree traversal that visits (applies handler()) each node in the tree data +// strucutre exactly once. + +void *rbtRoot(RbtHandle h); +// returns the root of the tree #endif /* RBTREE_H_ */ diff --git a/src/rbtree.c b/src/rbtree.c index 6b88fb87940..c6377fa7c18 100644 --- a/src/rbtree.c +++ b/src/rbtree.c @@ -434,3 +434,24 @@ void *rbtFind(RbtHandle h, void *key) { } return NULL; } + +void rbtTraversal(RbtHandle h, RbtIterator it, void *handler_arg, + void(*handler)(void *arg, RbtIterator it)) { + RbtType *rbt = h; + NodeType *root = it; + + // apply handler for: + // -o the root of the tree/subtree + handler(handler_arg, it); + // - the left subtree + if (root->left != SENTINEL) + rbtTraversal(h, root->left, handler_arg, handler); + // - the right subtree + if (root->right != SENTINEL) + rbtTraversal(h, root->right, handler_arg, handler); +} + +void *rbtRoot(RbtHandle h) { + RbtType *rbt = h; + return rbt->root; +}