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

Green YOUR SCHOOL!

Click here to get involved with dosomething.org!

John Krasinski's BIG MIRACLE

Click to watch the trailer and read exclusive star interviews!

Do you like Anna?

Read Dear Albert... from ANNA's perspective!

BATTLESHIP, the movie

Here's why we're super jazzed about it.

Do energy juices actually work?

Our blogger puts 'em to the test!


The Book

Cover image

Read What You Love, Anywhere You Like

Get Our FREE NOOK Reading Apps