Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.List;
- class Drink {
- private String name;
- private List<Drink> children;
- public Drink(String name) {
- this.name = name;
- this.children = new ArrayList<>();
- }
- public void addChild(Drink drink) {
- children.add(drink);
- }
- public String getName() {
- return name;
- }
- public List<Drink> getChildren() {
- return children;
- }
- }
- public class DrinkHierarchy {
- public static void main(String[] args) {
- // Create the drink hierarchy
- Drink root = new Drink("Drinks");
- Drink hot = new Drink("Hot");
- Drink cold = new Drink("Cold");
- root.addChild(hot);
- root.addChild(cold);
- Drink tea = new Drink("Tea");
- Drink coffee = new Drink("Coffee");
- hot.addChild(tea);
- hot.addChild(coffee);
- Drink greenTea = new Drink("Green Tea");
- Drink blackTea = new Drink("Black Tea");
- tea.addChild(greenTea);
- tea.addChild(blackTea);
- Drink americano = new Drink("Americano");
- Drink latte = new Drink("Latte");
- Drink cappuccino = new Drink("Cappuccino");
- coffee.addChild(americano);
- coffee.addChild(latte);
- coffee.addChild(cappuccino);
- Drink nonAlcoholic = new Drink("Non-Alcoholic");
- Drink alcoholic = new Drink("Alcoholic");
- cold.addChild(nonAlcoholic);
- cold.addChild(alcoholic);
- Drink cola = new Drink("Cola");
- Drink fanta = new Drink("Fanta");
- Drink soda = new Drink("Soda");
- nonAlcoholic.addChild(cola);
- nonAlcoholic.addChild(fanta);
- nonAlcoholic.addChild(soda);
- Drink wine = new Drink("Wine");
- Drink beer = new Drink("Beer");
- Drink whisky = new Drink("Whisky");
- alcoholic.addChild(wine);
- alcoholic.addChild(beer);
- alcoholic.addChild(whisky);
- // Print the drink hierarchy using pre-order traversal
- printDrinkHierarchy(root, 0);
- }
- public static void printDrinkHierarchy(Drink drink, int level) {
- StringBuilder indent = new StringBuilder();
- for (int i = 0; i < level; i++) {
- indent.append(" ");
- }
- System.out.println(indent + drink.getName());
- for (Drink child : drink.getChildren()) {
- printDrinkHierarchy(child, level + 1);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement