Problem 1: Tree Basics

Task 1: Find a Value in a Binary Tree

Now that we know the basics of traversing through a tree, implement binary search based on the process (or algorithm) we talked about in the previous page. Here’s a quick refresher:

SPOILER: Click here if you need help with the solution!
public static Node findValue(Node root, int value) {
    // We start at the root of the tree
    Node current = root;

    // We follow the logic we described above 
    while (current.value != value) {
        System.out.println("current value is: " + current.value);
        if (value < current.value) {
            current = current.left;
        }
        if (value > current.value) {
            current = current.right;
        }
    }

    // If we are here, we reached the node with
    // the correct value!
    return current;
}