solution using binary tree