Inserting in a BST

Iterative Insert (Using Tail Pointer) :

void insert(struct Node *ptr, int data) {

	// New node to be added
	struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
	newNode -> data = data;
	newNode -> left = newNode -> right = NULL;

	// Tail pointer 
	struct Node *parent = NULL;

	// If BST is empty, make new node as root node
	if (ptr == NULL) {
		root = newNode;
		return;
	}

	while (ptr != NULL) {
		
		// Move tail pointer to current node 
		parent = ptr;

		// Move current node to the next node
		if (ptr -> data == data) {
			// If the same data node is already present, free new node 
			free(newNode);
			return;
		}

		else if (data < ptr -> data)
			ptr = ptr -> left;
		else 
			ptr = ptr -> right;
	}

	if (data < parent -> data)
		parent -> left = newNode;
	else 
		parent -> right = newNode;

}

Iterative Insert (Without Using Tail Pointer) :

Recursive Insert :

Contributed by Nitin Ranganath

Last updated

Was this helpful?