Merging Cookie Orders - codepath/compsci_guides GitHub Wiki

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

Problem Highlights

  • 💡 Difficulty: Medium
  • Time to complete: 25 mins
  • 🛠️ Topics: Binary Trees, 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 one of the trees is None?
    • Return the other tree since there are no nodes to merge from the None tree.
  • What if both trees are None?
    • Return None since there are no nodes in either tree.
  • Are the trees guaranteed to be balanced?
    • The problem assumes the input trees are balanced when calculating time complexity.
HAPPY CASE
Input: order1 = [1, 3, 2, 5], order2 = [2, 1, 3, None, 4, None, 7]
Output: [3, 4, 5, 5, 4, None, 7]
Explanation: The merged tree has summed values where nodes overlap and the non-`None` node where they do not.

Input: order1 = [1, 2], order2 = [3]
Output: [4, 2]
Explanation: The merged tree takes the non-`None` node when there is no overlap.

EDGE CASE
Input: order1 = [], order2 = [1, 2, 3]
Output: [1, 2, 3]
Explanation: Since the first tree is empty, the merged tree is just the second tree.

Input: order1 = [4], order2 = []
Output: [4]
Explanation: Since the second tree is empty, the merged tree is just the first tree.

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 merging binary trees, we can consider the following approaches:

  • Recursion: Use recursion to traverse both trees simultaneously and merge nodes.
  • Tree Traversal: Traverse the trees in pre-order fashion (root, left, right) to sum the nodes or take the non-None node when only one node exists.

3: P-lan

Plan the solution with appropriate visualizations and pseudocode.

Plan

  1. Base Case:
    • If either order1 or order2 is None, return the other tree.
  2. Recursive Merge:
    • Sum the values of the current nodes from both trees.
    • Recursively merge the left and right children.
  3. Return: Return the merged tree starting from the root.

Recursive Implementation

Pseudocode:

1) Define the base case:
   * If `order1` is `None`, return `order2`.
   * If `order2` is `None`, return `order1`.

2) Create a new node with value equal to the sum of `order1.val` and `order2.val`.

3) Recursively merge the left children of `order1` and `order2` and assign the result to the left child of the merged node.

4) Recursively merge the right children of `order1` and `order2` and assign the result to the right child of the merged node.

5) Return the merged node.

4: I-mplement

Implement the code to solve the algorithm.

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

def merge_orders(order1, order2):
    # Base case: if either node is None, return the other node
    if not order1:
        return order2
    if not order2:
        return order1
    
    # Merge the nodes
    merged = TreeNode(order1.val + order2.val)
    
    # Recursively merge the left and right children
    merged.left = merge_orders(order1.left, order2.left)
    merged.right = merge_orders(order1.right, order2.right)
    
    return merged

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 order1 = [1, 3, 2, 5] and order2 = [2, 1, 3, None, 4, None, 7]:
    • The merge process should correctly produce the tree [3, 4, 5, 5, 4, None, 7].

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 larger tree.

  • Time Complexity: O(N) because each node in the larger tree must be visited once.
  • Space Complexity: O(N) due to the recursive call stack and the space required to create the merged tree.