<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def _prepare_menu(self, node, flat=None):
 """ Prepare the menu hierarchy from the given device tree. :param Device node: root node of device hierarchy :returns: menu hierarchy as list """

        if flat is None:
            flat = self.flat
        ItemGroup = MenuSection if flat else SubMenu
        return [
            ItemGroup(branch.label, self._collapse_device(branch, flat))
            for branch in node.branches
            if branch.methods or branch.branches
        ]