Tree query algorithm with Contains() method