-
Notifications
You must be signed in to change notification settings - Fork 0
/
2-binary_tree_insert_right.c
38 lines (34 loc) · 1.1 KB
/
2-binary_tree_insert_right.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include "binary_trees.h"
/**
* binary_tree_insert_right -Function inserts a node as
* the right-child of another
* @parent: is a pointer to the parent node to insert the right-child in
* @value: is the value to store in the newly created node
* description- when parent already has a right-child it should be replaced.
* and the replaced values made the right child of inserted node
*
* Return: NULL on Failure or parent(NULL) else a pointer
* to variable-allocated memory space
*/
binary_tree_t *binary_tree_insert_right(binary_tree_t *parent, int value)
{
/*Allocate memory for new node*/
binary_tree_t *newNode = malloc(sizeof(binary_tree_t));
/* verify memory allocation was successful*/
/* Also check that parent is not NULL*/
if (!newNode)
return (NULL);
if (!parent)
return (NULL);
/* set value to the created node*/
newNode->n = value;
newNode->parent = parent;
/*left child should be set to NULL*/
newNode->left = NULL;
newNode->right = parent->right;
parent->right = newNode;
/* if parent has a right node */
if (newNode->right)
newNode->right->parent = newNode;
return (newNode);
}