beyondgrader.com Logo
DemoBrowseAboutTeamLogin

Binary Tree Search Path

Geoffrey Challen // 2020.11.0

Let's continue exploring recursion on binary trees. However, this problem takes a significant step forward in difficulty, so be prepared!

We've provided a public class BinaryTreePath with a single class method pathToValue. pathToValue accepts a BinaryTree<Object> as its first parameter and an Object as its second. It returns a List<Object> containing all the values in the tree on the way to the first node with a value equal to the passed Object, or null if the tree does not contain the passed Object. We've handled this case already for you in the starter code. However, you should fix pathToValue so that it throws an IllegalArgumentException if either the passed tree or the passed value is null.

Our wrapper method initializes the list properly and then calls a private helper method which performs the recursion. The helper should return true if the tree contains the value, and if it does also manipulate the list properly. If the tree does not contain the value it should return false. You will want to use add(int index, Object value) to add values to the front of the list as you work your way through the tree.

This problem is hard! Here's an outline of a solution to help get you started:

  • If you reach an empty tree, you can return false, since an empty tree does not contain the value
  • Otherwise, if this node contains the value, add yourself to the list, stop recursing, and return true.
  • Otherwise, first search your right subtree. If that succeeds, then this node is also part of the path and should be added. If not, try the left subtree.
  • If neither the right nor left subtree contains the node, you should return false and not modify the list, since this node is not on the path to the desired node.

Good luck and have fun!