Find a given element in Binary Search Tree

This can be done using recursive function as well as non -recursive function . In binary search tree average worst case time complexity is O(logn)

1. Recursive function:


static bool findAElelentInBinarySearchTree(treeNode * rootNode, int value) {

	//if root node itself is null
	if (rootNode == NULL)
		return 0;
	//if given value is equal to root Node value
	if (rootNode->val == value)
		return 1;
	else {
		if (rootNode->val > value)
			return tree::findAElelentInBinarySearchTree(rootNode->leftChild, value);
		if (rootNode->val < value)
			return tree::findAElelentInBinarySearchTree(rootNode->rightChild, value);
	}

}

2. Non-recursive function :


static bool findAElelentInBinarySearchTreeWithoutRecursion(treeNode *rootNode,
		int value) {

	if (rootNode == NULL)
		return 0;
	while (rootNode) {

		if (rootNode->val == value)
			return 1;
		if (rootNode->val > value)
			rootNode = rootNode->leftChild;
		else
			rootNode = rootNode->rightChild;
	}

      return 0;

}

above mention functions are member function of my Binary Search Tree ADT class 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