# HG changeset patch # User Mike Becker # Date 1727962955 -7200 # Node ID a018f5916d3baf2fbcb19e9bc52e8efd70c1c318 # Parent 5ed7f634f04620cb57935cc8b204fef7482efc9c add cxTreeSubtreeDepth() relates to #166 diff -r 5ed7f634f046 -r a018f5916d3b src/cx/tree.h --- a/src/cx/tree.h Thu Oct 03 15:38:05 2024 +0200 +++ b/src/cx/tree.h Thu Oct 03 15:42:35 2024 +0200 @@ -1091,6 +1091,16 @@ size_t cxTreeSubtreeSize(CxTree *tree, void *subtree_root); /** + * Determines the depth of the specified subtree. + * + * @param tree the tree + * @param subtree_root the root node of the subtree + * @return the tree depth including the \p subtree_root + */ +__attribute__((__nonnull__)) +size_t cxTreeSubtreeDepth(CxTree *tree, void *subtree_root); + +/** * Creates a depth-first iterator for the specified tree. * * @param tree the tree to iterate diff -r 5ed7f634f046 -r a018f5916d3b src/tree.c --- a/src/tree.c Thu Oct 03 15:38:05 2024 +0200 +++ b/src/tree.c Thu Oct 03 15:42:35 2024 +0200 @@ -775,3 +775,15 @@ } return visitor.counter; } + +size_t cxTreeSubtreeDepth(CxTree *tree, void *subtree_root) { + CxTreeVisitor visitor = cx_tree_visitor( + subtree_root, + tree->loc_children, + tree->loc_next + ); + while (cxIteratorValid(visitor)) { + cxIteratorNext(visitor); + } + return visitor.depth; +} diff -r 5ed7f634f046 -r a018f5916d3b tests/test_tree.c --- a/tests/test_tree.c Thu Oct 03 15:38:05 2024 +0200 +++ b/tests/test_tree.c Thu Oct 03 15:42:35 2024 +0200 @@ -1609,6 +1609,21 @@ } } +CX_TEST(test_tree_high_subtree_depth) { + tree_node root = {0}, child1 = {0}, child2 = {0}, child3 = {0}; + cx_tree_link(&root, &child1, tree_node_layout); + cx_tree_link(&root, &child2, tree_node_layout); + cx_tree_link(&child1, &child3, tree_node_layout); + CxTree *tree = cxTreeCreateWrapped(&root, tree_node_layout); + CX_TEST_DO { + CX_TEST_ASSERT(cxTreeSubtreeDepth(tree, &root) == 3); + CX_TEST_ASSERT(cxTreeSubtreeDepth(tree, &child1) == 2); + CX_TEST_ASSERT(cxTreeSubtreeDepth(tree, &child2) == 1); + CX_TEST_ASSERT(cxTreeSubtreeDepth(tree, &child3) == 1); + } + cxTreeDestroy(tree); +} + CxTestSuite *cx_test_suite_tree_low_level(void) { CxTestSuite *suite = cx_test_suite_new("tree (low level)"); @@ -1651,6 +1666,7 @@ cx_test_register(suite, test_tree_high_create); cx_test_register(suite, test_tree_high_create_simple); cx_test_register(suite, test_tree_high_create_wrapped); + cx_test_register(suite, test_tree_high_subtree_depth); return suite; }