Codepath

Topsy Turvy

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 done if the tree is empty (hotel is None)?
    • Return None since there is nothing to flip.
  • What if the tree only has one node?
    • Return the single node as the tree does not need any flipping.
  • Can the tree have nodes with duplicate values?
    • Yes, the tree can contain duplicate node values, but that does not affect the flipping logic.
HAPPY CASE
Input: 
hotel = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3))

Output: 
[4, 5, 2, None, None, 3, 1]
Explanation: 
* The tree is flipped level by level according to the specified rules, resulting in the new structure.

Input: 
hotel = TreeNode(1, TreeNode(2), TreeNode(3))
Output: [2, None, 1, 3]
Explanation: 
* The tree is flipped, and the original root 1 becomes the right child, while the left child 2 becomes the new root.

EDGE CASE
Input: hotel = None
Output: None
Explanation: The tree is empty, so return `None`.

Input: hotel = TreeNode(1)
Output: [1]
Explanation: The tree has only one node, so return that node as it does not need flipping.

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 flipping or reversing the structure of a binary tree, we can consider the following approaches:

  • Recursion: Recursively traverse the tree and perform the flipping operations as you return from the base case.
  • Tree Manipulation: Adjust pointers in the tree to achieve the desired structure.

3: P-lan

Plan the solution with appropriate visualizations and pseudocode.

Plan

1) Base Case:

  • If the tree is empty or the tree has only one node (no left child), return the tree as is.

2) Recursive Case:

  • Recursively flip the left subtree to get the new root.
  • Perform the reassignment of pointers:
    • The original left child becomes the new root.
    • The original root becomes the right child of the new root.
    • The original right child becomes the left child of the new root.

3) Return the New Root:

  • After performing the necessary pointer reassignments, return the new root of the tree.

DFS Implementation

Pseudocode:

1) If `hotel` is `None` or has no left child, return `hotel`.

2) Recursively flip the left subtree to get the new root.

3) Reassign pointers:
    * `hotel.left.left = hotel.right` (original right child becomes new left child)
    * `hotel.left.right = hotel` (original root becomes new right child)
    * Set `hotel.left = None` and `hotel.right = None`.

4) Return the new root of the tree.

4: I-mplement

Implement the code to solve the algorithm.

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

def flip_hotel(hotel):
    if not hotel or not hotel.left:
        return hotel
    
    # Recursively flip the left subtree
    new_root = flip_hotel(hotel.left)
    
    # Perform the reassignments
    hotel.left.left = hotel.right  # The original right child becomes the new left child
    hotel.left.right = hotel       # The original root becomes the new right child
    
    # Set the current root's left and right children to None
    hotel.left = None
    hotel.right = None
    
    return new_root

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 = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3)):
    • The recursion should correctly flip the tree according to the specified rules, resulting in the new structure:
    4
  /   \
 5     2
      / \
     3   1

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) because each node in the tree must be visited and processed once.
  • Space Complexity: O(N) due to the recursive call stack, which can go as deep as the height of the tree.
Fork me on GitHub