954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Tree Insertion using a double pointer

Hi there, I'm working on a map for a class assignment and running into trouble. I've tried looking around the web but couldn't find anything that helped. I know how insertion works on a basic level when returning a node pointer but think i'm missing some key ideas when using a double pointer. Below i have the node struct declaration, the create node function, and my attempt at insert. Any help would be very very appreciated. Thanks so much for taking the time to look over this.

Given this:

NODE STRUCT:

struct Node {
  int    key;
  int    value;
  struct Node *left;
  struct Node *right;
  struct Node *parent;
};

and the create node function:

struct Node* create(int key, int value, struct Node* parent,int *perror) 
{
	struct Node* new = (struct Node*)malloc(sizeof(struct Node));
	if (!new) { *perror=E_NO_MEMORY; return 0; }
	new->key = key;
	new->value = value;
	new->left=0;
	new->right=0;
	new->parent=parent;
	*perror=0;
	return new;
}

And my attempt at inserting using recursion:

int insert_recursive(Node_handle* ppRoot, int key, int value) 
{
    Node_handle curr = *ppRoot;
    
    if (curr->parent == NULL)
    {
        int *perror;
        curr->parent = create(key, value, curr, perror);
        return *perror;
    }
    else
    {
        if (curr->key > key)
            return insert_recursive(&(curr->left), key, value);
        else
            return insert_recursive(&(curr->right), key, value);
    }
    
}

I've also tried passing curr->left/*right*/->parent into insert...God Help ME

Nicco
Newbie Poster
11 posts since Jun 2010
Reputation Points: 10
Solved Threads: 0
 

Im sorry Node_handle is a typedef for node*...if there was confusion

Nicco
Newbie Poster
11 posts since Jun 2010
Reputation Points: 10
Solved Threads: 0
 

Never mind I Figured it out!

Nicco
Newbie Poster
11 posts since Jun 2010
Reputation Points: 10
Solved Threads: 0
 

For the record, hiding a pointer behind a typedef is a fantastic way to confuse both yourself and others.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 
For the record, hiding a pointer behind a typedef is a fantastic way to confuse both yourself and others.


Yeah This is an assignment for school that was half implemented. So i have to use what i was given. I agree though!

Nicco
Newbie Poster
11 posts since Jun 2010
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: