simplify wm_postorder_traversal

This commit is contained in:
Akos Horvath 2024-04-07 13:43:43 +02:00
parent cca3845a4d
commit e261a7b518

View File

@ -384,61 +384,21 @@ UIntArray* wm_treenode_all_lmds_index(TreeNode *node)
return ret; return ret;
} }
static void traversal(TreeNode *node, NodeArray *arr)
{
if (!node) return;
for (size_t i = 0; i < node->children->size; i++)
traversal(node->children->nodes[i], arr);
wm_nodearray_push(arr, node);
}
NodeArray* wm_postorder_traversal(TreeNode *tree) NodeArray* wm_postorder_traversal(TreeNode *tree)
{ {
assert(tree);
TreeNode *root = tree;
typedef struct {
TreeNode *node;
size_t index;
} NodeWithIndex;
int root_index = 0;
NodeArray* stack = wm_nodearray_new();
NodeArray *ret = wm_nodearray_new(); NodeArray *ret = wm_nodearray_new();
while (root != NULL || stack->size > 0) { traversal(tree, ret);
if (root != NULL) {
NodeWithIndex *n = malloc(sizeof(NodeWithIndex));
assert(n);
n->node = root;
n->index = root_index;
wm_nodearray_push(stack, (void*)n);
root_index = 0;
if (root->children->size >= 1)
root = root->children->nodes[0];
else root = NULL;
continue;
}
NodeWithIndex *nptr;
wm_nodearray_pop(stack, (TreeNode**)(void**)&nptr);
NodeWithIndex n = *nptr;
free(nptr);
wm_nodearray_push(ret, n.node);
while (stack->size > 0 && n.index == ((NodeWithIndex**)stack->nodes)
[stack->size-1]->node->children->size - 1) {
wm_nodearray_pop(stack, (TreeNode**)(void**)&nptr);
n = *nptr;
free(nptr);
wm_nodearray_push(ret, n.node);
}
if (stack->size > 0) {
root = ((NodeWithIndex**)stack->nodes)[stack->size-1]->node
->children->nodes[n.index + 1];
root_index = n.index + 1;
}
}
wm_nodearray_free(stack);
return ret; return ret;
} }