Skip to content

Purging Unwanted Guests

kyra-ptn edited this page Sep 3, 2024 · 3 revisions

Unit 9 Session 1 (Click for link to problem statements)

Problem Highlights

  • 💡 Difficulty: Medium
  • Time to complete: 25-30 mins
  • 🛠️ Topics: Binary Trees, Tree Traversal, Recursion

1: U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Established a set (2-3) of test cases to verify their own solution later.
  • Established a set (1-2) of edge cases to verify their solution handles complexities.
  • Have fully understood the problem and have no clarifying questions.
  • Have you verified any Time/Space Constraints for this problem?
  • What should be returned if the tree is empty (hotel is None)?
    • Return an empty list since there are no rooms to purge.
  • Can the tree contain duplicate values?
    • Yes, the tree can contain duplicate guest values, and these should be considered when purging the leaves.
  • Are the node values unique?
    • The problem does not specify whether node values are unique, but it does not affect the solution.
HAPPY CASE
Input: 
hotel = Room("👻", Room("😱", Room("💀"), Room("😈")), Room("🧛🏾‍♀️"))
Output: [['💀', '😈', '🧛🏾‍♀️'], ['😱'], ['👻']]
Explanation: 
* The tree is purged level by level, with the leaf nodes being collected and removed first.

Input: 
hotel = Room("👻", Room("😱"), Room("🧛🏾‍♀️"))
Output: [['😱', '🧛🏾‍♀️'], ['👻']]
Explanation: 
* The tree is purged, and the leaf nodes "😱" and "🧛🏾‍♀️" are collected first, followed by the root "👻".

EDGE CASE
Input: hotel = None
Output: []
Explanation: The tree is empty, so return an empty list.

Input: hotel = Room("👻")
Output: [['👻']]
Explanation: The tree has only one node, so collect the single leaf node "👻" and return it.

2: M-atch

Match what this problem looks like to known categories of problems, e.g., Linked List or Dynamic Programming, and strategies or patterns in those categories.

For problems involving repeatedly removing leaf nodes from a binary tree, we can consider the following approaches:

  • Tree Traversal: Use recursion to traverse the tree and identify leaf nodes. After collecting the leaf nodes, modify the tree by removing them.
  • Depth-First Search (DFS): Use DFS to explore the tree and collect leaf nodes before removing them.

3: P-lan

Plan the solution with appropriate visualizations and pseudocode.

Plan

  1. Base Case:
    • If the hotel is empty (None), return an empty list since there are no rooms to purge.
  2. Recursive Function:
    • Implement a recursive function to collect leaf nodes:
      • Traverse the tree using DFS.
      • If a node is a leaf (has no children), add its value to a list and disconnect it from its parent.
      • Return True if the node is a leaf, so that it can be removed.
    • After collecting the leaf nodes, append them to the result list.
  3. Repeat:
    • Repeat the process of collecting and removing leaf nodes until the tree is empty.
    • Return the result list containing the collections of leaf nodes.

DFS Implementation

Pseudocode:

1) If `hotel` is `None`, return an empty list.

2) Initialize an empty list `result` to store the collections of leaf nodes.

3) Define a recursive function `collect_leaves(node, parent, is_left)`:
    a) If the node is `None`, return `False`.
    b) If the node is a leaf, add its value to the `leaves` list, disconnect it from its parent, and return `True`.
    c) Recur on the left and right children.
    d) Return `False` after processing the children.

4) While the tree is not empty:
    a) Initialize an empty list `leaves` to store the current collection of leaf nodes.
    b) Call `collect_leaves` starting with the root node.
    c) Append the `leaves` list to `result`.

5) Return the `result` list.

4: I-mplement

Implement the code to solve the algorithm.

class TreeNode:
    def __init__(self, value, left=None, right=None):
        self.val = value
        self.left = left
        self.right = right

def purge_hotel(hotel):
    def collect_leaves(node, parent, is_left):
        if not node:
            return False
        
        if not node.left and not node.right:  # Node is a leaf
            leaves.append(node.val)
            if parent:  # Disconnect this node from its parent
                if is_left:
                    parent.left = None
                else:
                    parent.right = None
            return True
        
        # Recurse on left and right children
        collect_leaves(node.left, node, True)
        collect_leaves(node.right, node, False)
        return False
    
    result = []
    
    while hotel:
        leaves = []
        if collect_leaves(hotel, None, False):  # If the root is a leaf
            hotel = None  # Entire tree is a single node, set to None
        result.append(leaves)
    
    return result

5: R-eview

Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.

  • Trace through your code with the input hotel = Room("👻", Room("😱", Room("💀"), Room("😈")), Room("🧛🏾‍♀️")):
    • The DFS should correctly identify and remove the leaf nodes level by level, appending each collection of leaves to result.

6: E-valuate

Evaluate the performance of your algorithm and state any strong/weak or future potential work.

Assume N represents the number of nodes in the tree.

  • Time Complexity: O(N^2) in the worst case, as each node may need to be revisited multiple times while collecting and removing leaves.
  • Space Complexity: O(N) due to the recursive call stack and the storage of leaf nodes in the result list.
Clone this wiki locally