Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have this function that I hope to be a good alternative to the recursive (thus performance expensive) approach.

#define _free_all(node, yes_no) \
    do { \
        Tree *__i;
        for (__i = node; __i; __i = __i->yes_no); \
        free(; node != __i; __i = __i->parent) { \
            free(__i->value); \
            free(__i); \
        } \
    } while (0)

void Tree_destroy(tree)
    Tree *tree;
{ /* Destroys a Tree object - Non Recursive */
    if (!tree)
        return;
    _free_all(tree, yes);
    _free_all(tree, no);

    if (tree->parent) {
        if (tree->parent->no == info)
            tree->parent->no = NULL;
        else
            tree->parent->yes = NULL;
    }
    free(tree);
}

The two children of each parent are no and yes.

Are there any issues with this approach ?

share|improve this question
    
How are Info and Tree defined? –  Olaf Dietsche Nov 14 '14 at 22:45
    
@OlafDietsche: Nothing, I just forgot to rename it. I corrected that. –  Amr Ayman Nov 14 '14 at 22:59
    
Names starting with _ and __ are reserved and best if avoided. –  glampert Nov 15 '14 at 1:30
    
Have you actually tested this code? It doesn't free the whole tree. The free_all macro either frees only left nodes or only right nodes, which means that any node in your tree that isn't on the left edge or right edge won't be freed. –  JS1 Nov 15 '14 at 10:50
    
JS1's comment is exactly the kind of thing I was going to warn about; binary trees and recursion are so intimately tied that any iterative function to do the same work will probably be horrendously complicated, which could lead to missed edge cases, leading to segfaults and memory leaks. –  tsleyson Nov 15 '14 at 19:00

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.