add cxTreeSubtreeDepth()

Thu, 03 Oct 2024 15:42:35 +0200

author
Mike Becker <universe@uap-core.de>
date
Thu, 03 Oct 2024 15:42:35 +0200
changeset 903
a018f5916d3b
parent 902
5ed7f634f046
child 904
cdc49211d87f

add cxTreeSubtreeDepth()

relates to #166

src/cx/tree.h file | annotate | diff | comparison | revisions
src/tree.c file | annotate | diff | comparison | revisions
tests/test_tree.c file | annotate | diff | comparison | revisions
--- 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
--- 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;
+}
--- 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;
 }

mercurial