Last active
September 20, 2015 06:20
-
-
Save ahmedahamid/0d206426c3d9ef1971d1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
tree_node* insert(tree_node* n, int value) | |
{ | |
if (n == NULL) | |
{ | |
return NULL; | |
} | |
tree_node* x_parent = NULL; | |
tree_node* x = n; | |
while (x != NULL) | |
{ | |
if (value == x->data) | |
{ | |
return x; | |
} | |
x_parent = x; // Keep track of the last node we have visited. | |
if (value < x->data) | |
{ | |
x = x->left; | |
} | |
else | |
{ | |
x = x->right; | |
} | |
} | |
// | |
// x now points to NULL and x_parent points to the last node visited | |
// We compare value with the value stored at the node to which | |
// x_parent points in order to know whether we should insert value | |
// at x_parent->left or x_parent->right. | |
// | |
if (value < x_parent->data) | |
{ | |
x_parent->left = new tree_node(); | |
x_parent->left->data = value; | |
x_parent->left->left = x_parent->left->right = NULL; | |
return x_parent->left; | |
} | |
// else use x_parent->right | |
x_parent->right = new tree_node(); | |
x_parent->right->data = value; | |
x_parent->right->left = x_parent->right->right = NULL; | |
return x_parent->right; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment