Performing Breadth First Search recursively

后端 未结 21 2596
不思量自难忘°
不思量自难忘° 2020-11-28 01:12

Let\'s say you wanted to implement a breadth-first search of a binary tree recursively. How would you go about it?

Is it possible using only the call-stack

21条回答
  •  被撕碎了的回忆
    2020-11-28 01:41

    The dumb way:

    template
    struct Node { Node* left; Node* right; T value; };
    
    template
    bool searchNodeDepth(Node* node, Node** result, int depth, P pred) {
        if (!node) return false;
        if (!depth) {
            if (pred(node->value)) {
                *result = node;
            }
            return true;
        }
        --depth;
        searchNodeDepth(node->left, result, depth, pred);
        if (!*result)
            searchNodeDepth(node->right, result, depth, pred);
        return true;
    }
    
    template
    Node* searchNode(Node* node, P pred) {
        Node* result = NULL;
        int depth = 0;
        while (searchNodeDepth(node, &result, depth, pred) && !result)
            ++depth;
        return result;
    }
    
    int main()
    {
        // a c   f
        //  b   e
        //    d
        Node
            a = { NULL, NULL, "A" },
            c = { NULL, NULL, "C" },
            b = { &a, &c, "B" },
            f = { NULL, NULL, "F" },
            e = { NULL, &f, "E" },
            d = { &b, &e, "D" };
    
        Node* found = searchNode(&d, [](char* value) -> bool {
            printf("%s\n", value);
            return !strcmp((char*)value, "F");
        });
    
        printf("found: %s\n", found->value);
    
        return 0;
    }
    

提交回复
热议问题