Binary Search in Trees


Searching a Binary Search Tree

Once you have gone through the hard work of building a binary search tree for your data, the pay-off comes in the form of efficient searchs through the data set. Data in a binary search tree can be searched in O(log(n)) time. This makes it worthwhile to put frequently searched data sets into tree form.

The method we will use for finding data in a binary search tree is quite similar to the one that we used in Section 1 to find where in the tree to insert new elements. In other words, we will traverse the tree, going left or right according to whether the element we are looking for is less than or greater than the data in the current node. If the data we are looking for is actually in the tree, we will eventually find it. If not, we'll eventually run off the bottom of the tree.


int	int_present (tree_t *t, int data)
{
	if (t == NULL) {
		return 0;
	}

	return (data == t->data) 
		|| int_present (t->left, data)
		|| int_present (t->right, data);
}

Take a Study Break

SparkLife

Star Trek gets SEXY

Chris Pine and Zoe Saldana heat up the red carpet!

SparkLife

Are you afraid of relationships?

Auntie SparkNotes can help!

SparkLife

Wanna get JLaw's gorgeous glow?

Click here for simple, sexy makeup tricks!

SparkLife

Sexy starlet style

See every single look from the Met Gala!

SparkLife

Who'd be on your zombie-apocalypse crew?

We already dib'sed Genghis Khan.

Geek out!

The MindHut

Geeky Actors: Then and Now

Travel back in time!

The MindHut

Villains We Want These Actresses to Play

From super cute to super bad!

The MindHut

10 Movies Better Than Their Books

What do you think?

The MindHut

How To Look Like J-Law...

When you don't look like J-Law.

The MindHut

12 Scientific Inaccuracies in Into Darkness

What did Star Trek get wrong?

The Book

Cover image

Read What You Love, Anywhere You Like

Get Our FREE NOOK Reading Apps