Insert and return a new node to binary search tree

Viewed 38

I need to insert a new tree node to a binary search tree but also return the same node I inserted. I've seen few examples of how to insert new node, but the return value is always the tree root and not the new node.

Thats what I've done so far, the main function is updateTree

typedef struct treeNode
{
    int data;
    struct treeNode* left;
    struct treeNode* right;
}TreeNode;

typedef struct tree
{
    TreeNode* root;
}Tree;


TreeNode* updateTree(Tree* tree, int data)
{
    if (tree->root == NULL)
    {
        tree->root = createNode(data);
        return tree->root;
    }
    else
    {
        return insertNode(tree->root, data);
    }
}

TreeNode* insertNode(TreeNode* root, int data)
{
    if (root == NULL)
    {
        return createNode(data);
    }
    else if (data > root->data)
    {
        root->right = insertNode(root->right, data);
    }
    else
    {
        root->left = insertNode(root->left, data);
    }
    return root;
}

TreeNode* createNode(int data)
{
    TreeNode* node;

    node = (TreeNode*)malloc(sizeof(TreeNode));
    checkMemoryAllocation(node);

    node->data= data;

    node->left = NULL;
    node->right = NULL;

    return node;
}

My question is, how do I return the new node I created?

0 Answers
Related