Binary Trees - Depth First Traversal and Search

Binary Tree - Depth First Traversal (DFT)

Applications

Pre-Order Traversal

Algorithm

//
// depth first pre-order
//
void preorder (Node* head)
{
    if (!head)
        return;

    // e.g. visit
    std::cout << head << " ";

    preorder (head->left);
    preorder (head->right);
}

In-Order Traversal

Algorithm

//
// depth first in-order
//
void inorder (Node* head)
{
    if (!head)
        return;

    inorder (head->left);

    // e.g. visit
    std::cout << head << " ";

    inorder (head->right);
}

Post-Order Traversal

Algorithm

//
// depth first post-order
//
void postorder (Node* head)
{
    if (!head)
        return;

    postorder (head->left);
    postorder (head->right);

    // e.g. visit
    std::cout << head << " ";
}

Binary Tree - Depth First Search (DFS)

Algorithm

void dfs (Node* n, int end, std::vector<Node*>& path=std::vector<Node*>())
{
    if (!n)
        return;

    path.push_back(n);

    if (n->value == end)
    {
        print_path(path);
        return;
    }

    if (n->left)
        dfs(n->left, end, path);

    if (n->right)
        dfs(n-gt;right, end, path);
   
    path.pop_back();
}