Insert Elements in Binary Tree

It’s always easy to store elements in binary search tree(BST) because of its property and generally we forget about how to add elements in binary tree not in binary search tree(BST). Here is function which we can use to add elements in binary tree.

/*
 * binaryTree.cpp
 * Created on: 23-May-2014
 * Author: Gyaneshwar Pardhi
 */

void insertAElement(treeNode* Elem, int value) {
	treeNode *temp;

	//create a Queue
	queue<treeNode*> Q;
	treeNode *newNode = new treeNode(value);

	if (!this->root) {
		this->root = newNode;
		return;
	}

	Q.push(Elem);
	while (!Q.empty()) {
		temp = Q.front();
		Q.pop();
		if (temp->leftChild) {
			Q.push(temp->leftChild);
		} else {
			temp->leftChild = newNode;
			return;
		}

		if (temp->rightChild) {
			Q.push(temp->rightChild);

		} else {
			temp->rightChild = newNode;
			return;
		}

	}
}

above mention function is a member function of tree ADT you can check complete program here
A Developer
Gy@n!

About Gyaneshwar Pardhi

Exploring the world and trying to know how can i involve to make this perfect. Gy@n!
This entry was posted in c++, Data Structure, interview Question, Programming and tagged , , . Bookmark the permalink.

Leave a comment