简体   繁体   中英

Difference between iteration and recursion in binary search tree insertion

I am trying to implement insertion in a binary search tree. According to my logic, both the recursion and iteration are performing very similar tasks - however, my recursive function works but my iterative solution doesn't. What is the difference in execution? Why is the iteration function not working? (Ignore the different return types)

The error that occurs is that in the case of iteration, only one element gets inserted properly. Successive insertions do not work.

Class Definition :

class Node
{
    public:
        Node(int x, Node *l = NULL, Node *r = NULL)
        {
            val = x;
            left = l;
            right = r;
        }
        int val;
        Node *left;
        Node *right;
};

Iteration :

Node* insert(Node* &root, int x)
{
    Node* newNode = new Node(x);
    if (root == NULL)
    {
        root = newNode;
        return root;
    }
    else
    {
        Node* travNode = root;
        while (travNode != NULL)
        {
            if (x < travNode->val)
                travNode = travNode->left;
            else
                travNode = travNode->right;
        }
        travNode = newNode;
    }
    return root;
}

Recursion :

void insert(Node* &root, int x)
{
    if (root == NULL)
    {
        Node* newNode = new Node(x);
        root = newNode;
    }
    else
    {
        if (x < root->val)
            insert(root->left, x);
        else
            insert(root->right, x);
    }
}

Thanks !

In your recursion, your whole function executes when you call insert() which is correct.

In the iterative solution, you find a node which would be the parent node for your new node, but you overwrite that node with the new node instead of setting it as a child.

You need to have travNode->left = newNode or travNode->right = newNode somewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM