#include <stdlib.h>
#include "quadtree.h"
-#include "utils.h"
#ifdef DEBUG
#define debug 1
}
}
- children += node->child[i] + 1;
+ children += node->child[i]->children + 1;
validate_subtree(node->child[i]);
}
- if (node->children < 0) {
- printf("%s:%d Tree statistics inconsistency detected! "
- "Negative child count: %ld\n",
- __func__, __LINE__, node->children);
- }
-
if (node->depth < 0) {
printf("%s:%d Tree statistics inconsistency detected! "
"Negative depth: %ld\n",
return 0;
}
- parent->children++;
-
- if (parent->child[ret]) {
- quadtree_add(parent->child[ret], new, compare);
- parent->depth = MAX(parent->depth,
- parent->child[ret]->depth + 1);
- return new;
- }
+ if (parent->child[ret])
+ return quadtree_add(parent->child[ret], new, compare);
parent->child[ret] = new;
new->parent = parent;
+ quadtree_recalculate_parent_stats(parent);
+
validate_tree(new);
return new;
int (*compare)(struct quadtree *a,
struct quadtree *b))
{
- struct quadtree *parent = 0, *tmp;
+ struct quadtree *parent = 0;
int i;
/*
trap();
}
+ /* Fix parent stats */
+ quadtree_recalculate_parent_stats(node->parent);
+
/*
* The sub branch is now detached from the main tree. Continue
* relocating the detached branch.
node->child[i] = 0;
}
- /* Fix parent stats */
- tmp = parent;
- while (tmp) {
- tmp->children -= node->children;
- tmp->depth = 0;
- for (i = 0; i < 4; i++) {
- if (tmp->child[i])
- tmp->depth = MAX(tmp->depth,
- tmp->child[i]->depth + 1);
- }
- tmp = tmp->parent;
- }
-
parent = quadtree_find_parent(node);
node->parent = 0;
#include <string.h>
+#include "utils.h"
+
struct quadtree {
struct quadtree *child[4];
struct quadtree *parent;
return t;
}
+/*
+ * Recursively walk through the tree and propagate changes made to the
+ * given node up until the highest parent.
+ */
+static inline void quadtree_recalculate_parent_stats(struct quadtree *node)
+{
+ int i;
+
+ while (node) {
+ node->depth = 0;
+ node->children = 0;
+
+ for (i = 0; i < 4; i++) {
+ if (!node->child[i])
+ continue;
+
+ node->depth = MAX(node->depth,
+ node->child[i]->depth + 1);
+ node->children += node->child[i]->children + 1;
+ }
+
+ node = node->parent;
+ }
+}
+
#endif