How does the recursion work for the function provided?
struct tree
{
    int value;
    struct tree* left;
    struct tree* right;
};
void recursion(tree* head)
{
    if (head != NULL)
    {
        recursion(head->left);
        cout << head->value << endl;
        recursion(head->right);
    }
}
int main()
{
    tree* head;
    
    tree* newNode = new(struct tree);
    newNode->value = 2;
    newNode->left = NULL;
    newNode->right = NULL;
    head = newNode;
    newNode = new(struct tree);
    newNode->value = 1;
    newNode->left = NULL;
    newNode->right = NULL;
    head->left = newNode;
    newNode = new(struct tree);
    newNode->value = 3;
    newNode->left = NULL;
    newNode->right = NULL;
    head->right = newNode;
    recursion(head);
    return 0;
}
Traversing through the tree node with the recursion() function, during recursion(head->left) inside the function, when it finally hits NULL does the end of that state of recursion become 'head->value' and use the cout << head->value << endl; line of code to print 1? Vice versa for recursion(head->right)? I'm having a hard time understanding how exactly the last left node is being printed granted i'm only using cout for the head->value node.
Aucun commentaire:
Enregistrer un commentaire