{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "title",
   "metadata": {},
   "source": [
    "# Trees & Graphs\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "intro",
   "metadata": {},
   "source": [
    "Trees and graphs organize relationships. Trees model hierarchy; graphs model general connections.\n",
    "\n",
    "```text\n",
    "Outline\n",
    "\n",
    "Trees\n",
    "  o Root, children, leaves\n",
    "  o Recursive traversal\n",
    "Binary Trees\n",
    "  o Nodes and traversals\n",
    "  o Binary search trees\n",
    "Graphs\n",
    "  o Nodes and edges\n",
    "  o Adjacency lists\n",
    "Graph Traversal\n",
    "  o Breadth-first search\n",
    "  o Depth-first search\n",
    "```\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "contents",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 2\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "trees",
   "metadata": {},
   "source": [
    "## Trees\n",
    "\n",
    "A **tree** is a linked structure that starts at a single top node, the **root**. Each node can have children. A node that has children is the **parent** of each of them, and each of those nodes is a **child** of that node. Every node except the root has exactly one parent, and the root has none. A node with no children is called a **leaf**.\n",
    "\n",
    "Trees are useful for hierarchical data such as folders, organization charts, HTML documents, decision trees, and expression trees."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-trees",
   "metadata": {},
   "source": [
    "```{index} tree, root node, leaf node, parent node, child node\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "tree-code",
   "metadata": {},
   "outputs": [],
   "source": [
    "class TreeNode:\n",
    "    def __init__(self, value):\n",
    "        self.value = value\n",
    "        self.children = []\n",
    "\n",
    "    def add_child(self, child):\n",
    "        self.children.append(child)\n",
    "\n",
    "\n",
    "root = TreeNode(\"company\")\n",
    "analytics = TreeNode(\"analytics\")\n",
    "operations = TreeNode(\"operations\")\n",
    "\n",
    "root.add_child(analytics)\n",
    "root.add_child(operations)\n",
    "analytics.add_child(TreeNode(\"alice\"))\n",
    "analytics.add_child(TreeNode(\"bob\"))\n",
    "operations.add_child(TreeNode(\"charlie\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "tree-print",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "company\n  analytics\n    alice\n    bob\n  operations\n    charlie\n"
    }
   ],
   "source": [
    "def print_tree(node, level=0):\n",
    "    indent = \"  \" * level\n",
    "    print(indent + str(node.value))\n",
    "    for child in node.children:\n",
    "        print_tree(child, level + 1)\n",
    "\n",
    "\n",
    "print_tree(root)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "exercise-tree",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Add a Tree Node\n",
    "# Add a new employee named dana under operations.\n",
    "# Then print the tree again.\n",
    "# Print exactly:\n",
    "# company\n",
    "#   analytics\n",
    "#     alice\n",
    "#     bob\n",
    "#   operations\n",
    "#     charlie\n",
    "#     dana\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "solution-tree",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "company\n  analytics\n    alice\n    bob\n  operations\n    charlie\n    dana\n"
    }
   ],
   "source": [
    "### Solution\n",
    "operations.add_child(TreeNode(\"dana\"))\n",
    "print_tree(root)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "binary-trees",
   "metadata": {},
   "source": [
    "## Binary Trees\n",
    "\n",
    "A **binary tree** is a tree in which each node has at most two children, called the **left child** and the **right child**. Limiting each node to two children makes the structure simple to code, and it is the basis of binary search trees, which keep values in sorted order."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-binary-trees",
   "metadata": {},
   "source": [
    "```{index} binary tree\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "binary-tree-nodes",
   "metadata": {},
   "source": [
    "### Binary Tree Nodes\n",
    "\n",
    "A binary tree node stores a value and two links. Instead of the `children` list in `TreeNode`, each node has a `left` attribute and a `right` attribute. A link that points to no node is `None`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-binary-tree-nodes",
   "metadata": {},
   "source": [
    "```{index} Node class, left child, right child, tree height\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "binary-node-code",
   "metadata": {},
   "outputs": [],
   "source": [
    "class Node:\n",
    "    def __init__(self, value, left=None, right=None):\n",
    "        self.value = value\n",
    "        self.left = left\n",
    "        self.right = right"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "binary-tree-shape",
   "metadata": {},
   "source": [
    "The next cell builds this six-node tree by hand, one link at a time:\n",
    "\n",
    "```text\n",
    "        1\n",
    "      /   \\\n",
    "     2     3\n",
    "    / \\     \\\n",
    "   4   5     6\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "binary-tree-build",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "1\n2 3\nNone None\n"
    }
   ],
   "source": [
    "tree = Node(1)\n",
    "tree.left = Node(2)\n",
    "tree.right = Node(3)\n",
    "tree.left.left = Node(4)\n",
    "tree.left.right = Node(5)\n",
    "tree.right.right = Node(6)\n",
    "\n",
    "print(tree.value)                                  # 1\n",
    "print(tree.left.value, tree.right.value)           # 2 3\n",
    "print(tree.left.left.left, tree.left.left.right)   # None None"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "binary-tree-terms",
   "metadata": {},
   "source": [
    "The terms from the Trees section carry over. Node 1 is the **root**. Nodes 4, 5, and 6 are **leaves** because both of their links are `None`. Node 3 has only a right child, which a binary tree allows.\n",
    "\n",
    "The **height** of a tree is the number of levels on the longest path from the root down to a leaf. This tree has height 3, following the path 1, 2, 4. An empty tree has height 0. Some books count edges instead of levels, which gives this tree height 2; the O(h) cost in 13.1 grows the same way under either count.\n",
    "\n",
    "Each link also points to a smaller binary tree, called a **subtree**. The left subtree of node 1 is the tree rooted at node 2. Because every subtree is itself a binary tree, recursive functions fit this structure naturally."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "binary-traversals",
   "metadata": {},
   "source": [
    "### Traversals\n",
    "\n",
    "A **tree traversal** visits every node exactly once. In a binary tree, the three classic orders differ only in when you visit the node itself relative to its two subtrees:\n",
    "\n",
    "- **Preorder**: the node, then the left subtree, then the right subtree.\n",
    "- **Inorder**: the left subtree, then the node, then the right subtree.\n",
    "- **Postorder**: the left subtree, then the right subtree, then the node.\n",
    "\n",
    "Each function below follows the recursive pattern from {doc}`4.3 Recursion <../04-functions/0403-recursion>`. The base case is an empty tree (`None`), which contributes an empty list. The recursive case joins the node's value with the lists returned for its two subtrees."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-binary-traversals",
   "metadata": {},
   "source": [
    "```{index} tree traversal, preorder traversal, inorder traversal, postorder traversal\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "traversal-functions",
   "metadata": {},
   "outputs": [],
   "source": [
    "def preorder(node):\n",
    "    if node is None:\n",
    "        return []\n",
    "    return [node.value] + preorder(node.left) + preorder(node.right)\n",
    "\n",
    "\n",
    "def inorder(node):\n",
    "    if node is None:\n",
    "        return []\n",
    "    return inorder(node.left) + [node.value] + inorder(node.right)\n",
    "\n",
    "\n",
    "def postorder(node):\n",
    "    if node is None:\n",
    "        return []\n",
    "    return postorder(node.left) + postorder(node.right) + [node.value]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "traversal-run",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "[1, 2, 4, 5, 3, 6]\n[4, 2, 5, 1, 3, 6]\n[4, 5, 2, 6, 3, 1]\n"
    }
   ],
   "source": [
    "print(preorder(tree))    # [1, 2, 4, 5, 3, 6]\n",
    "print(inorder(tree))     # [4, 2, 5, 1, 3, 6]\n",
    "print(postorder(tree))   # [4, 5, 2, 6, 3, 1]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "traversal-uses",
   "metadata": {},
   "source": [
    "The three functions differ only in where `[node.value]` goes, and each order suits a different job:\n",
    "\n",
    "- **Preorder** visits a parent before its children, so it fits copying or serializing a tree: rebuilding nodes in this order always creates each parent before its children.\n",
    "- **Inorder** visits everything on the left before the node and everything on the right after it, so on a binary search tree (next subsection) it returns the values in sorted order.\n",
    "- **Postorder** visits children before their parent, so it fits work that needs the children finished first, such as deleting a tree from the bottom up or evaluating an expression tree, where an operator needs both operand values."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bst",
   "metadata": {},
   "source": [
    "### Binary Search Trees\n",
    "\n",
    "A **binary search tree** (BST) is a binary tree that keeps one ordering rule at every node: all values in the left subtree are smaller than the node's value, and all values in the right subtree are larger. The rule tells you which way to go at every step, so a search follows a single path from the root instead of visiting every node.\n",
    "\n",
    "`insert(root, value)` adds a value and returns the root of the updated tree. If the tree is empty, the new node becomes the root. Otherwise, the function compares the value with the current node and inserts into the left or right subtree. This version ignores duplicates. `contains(root, value)` follows the same path with a loop, stopping when it finds the value or reaches `None`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-bst",
   "metadata": {},
   "source": [
    "```{index} binary search tree, BST insertion, BST search, degenerate tree\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bst-code",
   "metadata": {},
   "outputs": [],
   "source": [
    "def insert(root, value):\n",
    "    if root is None:\n",
    "        return Node(value)\n",
    "    if value < root.value:\n",
    "        root.left = insert(root.left, value)\n",
    "    elif value > root.value:\n",
    "        root.right = insert(root.right, value)\n",
    "    return root\n",
    "\n",
    "\n",
    "def contains(root, value):\n",
    "    node = root\n",
    "    while node is not None:\n",
    "        if value == node.value:\n",
    "            return True\n",
    "        if value < node.value:\n",
    "            node = node.left\n",
    "        else:\n",
    "            node = node.right\n",
    "    return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bst-build",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "True\nFalse\n[20, 30, 40, 50, 60, 70, 80]\n"
    }
   ],
   "source": [
    "bst = None\n",
    "for num in [50, 30, 70, 20, 40, 60, 80]:\n",
    "    bst = insert(bst, num)\n",
    "\n",
    "print(contains(bst, 60))   # True\n",
    "print(contains(bst, 65))   # False\n",
    "print(inorder(bst))        # [20, 30, 40, 50, 60, 70, 80]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bst-shape",
   "metadata": {},
   "source": [
    "The values went in unsorted, but inorder traversal returns them sorted. The ordering rule guarantees it: everything to the left of a node is smaller, and everything to the right is larger. The insertions build this tree:\n",
    "\n",
    "```text\n",
    "          50\n",
    "        /    \\\n",
    "      30      70\n",
    "     /  \\    /  \\\n",
    "   20   40  60   80\n",
    "```\n",
    "\n",
    "Searching for 60 checks 50, then 70, then 60: three steps for seven values, because the tree has height 3."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bst-degenerate",
   "metadata": {},
   "source": [
    "The shape of a BST depends on the order of insertion. The next cell inserts values that are already sorted and then walks down the right links, reporting whether each node has a left child."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bst-chain",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "20 has left child: False\n30 has left child: False\n40 has left child: False\n50 has left child: False\n60 has left child: False\n"
    }
   ],
   "source": [
    "chain = None\n",
    "for num in [20, 30, 40, 50, 60]:\n",
    "    chain = insert(chain, num)\n",
    "\n",
    "node = chain\n",
    "while node is not None:\n",
    "    print(node.value, \"has left child:\", node.left is not None)\n",
    "    node = node.right"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bst-cost",
   "metadata": {},
   "source": [
    "Each new value is larger than everything already in the tree, so it always goes to the right. The result is a **degenerate tree**: a chain in which every node has at most one child, and the height equals the number of nodes.\n",
    "\n",
    "As {doc}`13.1 ADT Basics <1301-adt-basics>` explains, BST lookup costs O(h), where h is the height. In a balanced tree like `bst`, h grows like log₂ n, so lookups stay fast as the tree grows. In `chain`, h = n, so `contains(chain, 60)` checks all five nodes, which is no better than scanning a list. Self-balancing trees avoid this by restructuring themselves as values are inserted."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "exercise-binary-tree",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Tree Height\n",
    "# Write a function tree_height(node) that returns the number of levels in a binary tree.\n",
    "# An empty tree (None) has height 0, and a single node has height 1.\n",
    "# Then print the heights of tree, bst, and chain.\n",
    "# Print exactly:\n",
    "# 3\n",
    "# 3\n",
    "# 5\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "solution-binary-tree",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "3\n3\n5\n"
    }
   ],
   "source": [
    "### Solution\n",
    "def tree_height(node):\n",
    "    if node is None:\n",
    "        return 0\n",
    "    return 1 + max(tree_height(node.left), tree_height(node.right))\n",
    "\n",
    "\n",
    "print(tree_height(tree))\n",
    "print(tree_height(bst))\n",
    "print(tree_height(chain))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "graphs",
   "metadata": {},
   "source": [
    "## Graphs\n",
    "\n",
    "A **graph** stores relationships between items. The items are **nodes** (also called vertices), and the relationships are **edges**.\n",
    "\n",
    "A common Python representation is an **adjacency list**: a dictionary where each key maps to a list of neighbors. In the friendship graph below, each connection goes both ways, so every edge is stored twice: `\"bob\"` appears in alice's list, and `\"alice\"` appears in bob's list."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-graphs",
   "metadata": {},
   "source": [
    "```{index} graph, adjacency list, graph edge\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "graph-code",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "['bob', 'charlie']\n"
    }
   ],
   "source": [
    "graph = {\n",
    "    \"alice\": [\"bob\", \"charlie\"],\n",
    "    \"bob\": [\"alice\", \"dana\"],\n",
    "    \"charlie\": [\"alice\", \"dana\"],\n",
    "    \"dana\": [\"bob\", \"charlie\"],\n",
    "}\n",
    "\n",
    "print(graph[\"alice\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "exercise-graph",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Add a Graph Edge\n",
    "# Add a new person named erin who is connected to dana.\n",
    "# Update both adjacency lists so the relationship works both ways.\n",
    "# Then print graph[\"dana\"].\n",
    "# Print exactly:\n",
    "# ['bob', 'charlie', 'erin']\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "solution-graph",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "['bob', 'charlie', 'erin']\n"
    }
   ],
   "source": [
    "### Solution\n",
    "graph[\"erin\"] = [\"dana\"]\n",
    "graph[\"dana\"].append(\"erin\")\n",
    "\n",
    "print(graph[\"dana\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "traversal",
   "metadata": {},
   "source": [
    "## Graph Traversal\n",
    "\n",
    "A traversal visits nodes systematically.\n",
    "\n",
    "- **Breadth-first search** uses a queue and explores nearby nodes first.\n",
    "- **Depth-first search** uses a stack or recursion and follows one path before backing up."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-traversal",
   "metadata": {},
   "source": [
    "```{index} graph traversal, breadth-first search, depth-first search\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bfs-heading",
   "metadata": {},
   "source": [
    "### Breadth-First Search\n",
    "\n",
    "The examples below use `graph` as it stands after the Add a Graph Edge exercise, with erin connected to dana. Run that exercise's solution first if you are following along.\n",
    "\n",
    "`breadth_first_search` takes the oldest node from the queue, records it, and adds its neighbors to the back. The `visited` set matters because a node can be reached along more than one path: dana is a neighbor of both bob and charlie, so without the set she would be recorded twice. `graph.get(node, [])` treats a node with no entry in the dictionary as having no neighbors."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "traversal-code",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "['alice', 'bob', 'charlie', 'dana', 'erin']\n"
    }
   ],
   "source": [
    "from collections import deque\n",
    "\n",
    "\n",
    "def breadth_first_search(graph, start):\n",
    "    visited = set()\n",
    "    order = []\n",
    "    queue = deque([start])\n",
    "\n",
    "    while queue:\n",
    "        node = queue.popleft()\n",
    "        if node in visited:\n",
    "            continue\n",
    "\n",
    "        visited.add(node)\n",
    "        order.append(node)\n",
    "\n",
    "        for neighbor in graph.get(node, []):\n",
    "            if neighbor not in visited:\n",
    "                queue.append(neighbor)\n",
    "\n",
    "    return order\n",
    "\n",
    "\n",
    "print(breadth_first_search(graph, \"alice\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "exercise-traversal",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Stop at a Target\n",
    "# Write bfs_until(graph, start, target), a copy of breadth_first_search that\n",
    "# returns the visited order as soon as target is visited.\n",
    "# Call bfs_until(graph, \"alice\", \"charlie\") and print the result.\n",
    "# Print exactly:\n",
    "# ['alice', 'bob', 'charlie']\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "solution-traversal",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "['alice', 'bob', 'charlie']\n"
    }
   ],
   "source": [
    "### Solution\n",
    "def bfs_until(graph, start, target):\n",
    "    visited = set()\n",
    "    order = []\n",
    "    queue = deque([start])\n",
    "\n",
    "    while queue:\n",
    "        node = queue.popleft()\n",
    "        if node in visited:\n",
    "            continue\n",
    "\n",
    "        visited.add(node)\n",
    "        order.append(node)\n",
    "\n",
    "        if node == target:\n",
    "            return order\n",
    "\n",
    "        for neighbor in graph.get(node, []):\n",
    "            if neighbor not in visited:\n",
    "                queue.append(neighbor)\n",
    "\n",
    "    return order\n",
    "\n",
    "\n",
    "print(bfs_until(graph, \"alice\", \"charlie\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dfs-intro",
   "metadata": {},
   "source": [
    "### Depth-First Search\n",
    "\n",
    "Depth-first search follows one path as far as possible before backing up. It uses a stack, either explicitly or through recursion. Because `stack.pop()` takes the neighbor pushed last, this version explores alice's last neighbor, charlie, before bob."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dfs-code",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "['alice', 'charlie', 'dana', 'erin', 'bob']\n"
    }
   ],
   "source": [
    "def depth_first_search(graph, start):\n",
    "    visited = set()\n",
    "    order = []\n",
    "    stack = [start]\n",
    "\n",
    "    while stack:\n",
    "        node = stack.pop()\n",
    "        if node in visited:\n",
    "            continue\n",
    "\n",
    "        visited.add(node)\n",
    "        order.append(node)\n",
    "\n",
    "        for neighbor in graph.get(node, []):\n",
    "            if neighbor not in visited:\n",
    "                stack.append(neighbor)\n",
    "\n",
    "    return order\n",
    "\n",
    "\n",
    "print(depth_first_search(graph, \"alice\"))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "exercise-dfs",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Compare Traversal Orders\n",
    "# Call both breadth_first_search and depth_first_search on graph starting from \"alice\".\n",
    "# Print both results. Then print the data structure each function uses to hold the\n",
    "# nodes still to visit: \"BFS uses: \" and \"DFS uses: \", each followed by \"queue\" or \"stack\".\n",
    "# Print exactly:\n",
    "# ['alice', 'bob', 'charlie', 'dana', 'erin']\n",
    "# ['alice', 'charlie', 'dana', 'erin', 'bob']\n",
    "# BFS uses: queue\n",
    "# DFS uses: stack\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "solution-dfs",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['alice', 'bob', 'charlie', 'dana', 'erin']\n",
      "['alice', 'charlie', 'dana', 'erin', 'bob']\n",
      "BFS uses: queue\n",
      "DFS uses: stack\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "print(breadth_first_search(graph, \"alice\"))\n",
    "print(depth_first_search(graph, \"alice\"))\n",
    "\n",
    "# BFS visits neighbors level by level (nearest first).\n",
    "# DFS follows one neighbor chain as far as possible before backtracking.\n",
    "# The order differs because BFS uses a queue (FIFO) and DFS uses a stack (LIFO).\n",
    "print(\"BFS uses: queue\")\n",
    "print(\"DFS uses: stack\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
