Solution Review: Search Value in a Binary Tree

Let’s take a detailed look at the previous challenge’s solution.

Solution

To find if a value exists in a binary tree, we’ll use the exhaustive search algorithm. First, we’ll compare the value in the current node with our key. If it matches, we end our search. If it doesn’t, we’ll recursively look for the key in the left and right subtrees. We’ll stop when we find our desired key in the tree or if the tree is traversed completely, whichever comes first. We can code this algorithm as follows:

Code

Get hands-on with 1400+ tech skills courses.