Code

avltree: Iterate through the tree depth-first when clearing it.
authorSebastian Harl <sh@tokkee.org>
Fri, 11 Jul 2014 15:42:33 +0000 (17:42 +0200)
committerSebastian Harl <sh@tokkee.org>
Fri, 11 Jul 2014 15:42:33 +0000 (17:42 +0200)
Else, we cannot simple delete each node but we'd have to actually remove it
from the tree because we'd be removing non-leaf nodes.

Don't use recursion for iterating the tree. It's not needed and would
consume stack-space unnecessarily. The current approach limits the size of the
tree by heap memory only.

src/utils/avltree.c

index 7397a34fdbb56dfd54d4db07c82f797cf3d93b76..aad2b9a6e8282d10ff0dd3764d920b681f992837 100644 (file)
@@ -154,9 +154,30 @@ tree_clear(sdb_avltree_t *tree)
 {
        node_t *n;
 
-       n = node_smallest(tree);
+       if ((! tree) || (! tree->root))
+               return;
+
+       /* do a depth-first iteration and delete the leafs */
+       n = tree->root;
        while (n) {
-               node_t *tmp = node_next(n);
+               node_t *tmp;
+
+               if (n->left) {
+                       n = n->left;
+                       continue;
+               }
+               else if (n->right) {
+                       n = n->right;
+                       continue;
+               }
+
+               tmp = n->parent;
+               if (tmp) {
+                       if (tmp->left == n)
+                               tmp->left = NULL;
+                       else
+                               tmp->right = NULL;
+               }
 
                node_destroy(n);
                n = tmp;