Change back button into a menu button when there are no pages to go back

I have a page which can be accessed directly or by going through a couple of other pages. When accessed directly it should show a menu toggle button. If accessed through another page it should show a back button.

How do I add a menu toggle button which will change into a back button only if there are pages for it to go back?