Implementing the tree search