#951

Flip Equivalent Binary Trees

Medium
TreeDepth-First SearchBinary TreeRecursionTree Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses recursion but avoids unnecessary checks by directly comparing the nodes and their children in a single pass. This reduces redundant calculations and improves efficiency.

⚙️

Algorithm

4 steps
  1. 1Step 1: If both nodes are null, return true.
  2. 2Step 2: If one node is null and the other is not, return false.
  3. 3Step 3: If the values of the nodes are different, return false.
  4. 4Step 4: Recursively check both configurations without flipping and with flipping, but only once for each configuration.
solution.py8 lines
1def flipEquiv(root1, root2):
2    if not root1 and not root2:
3        return True
4    if not root1 or not root2:
5        return False
6    if root1.val != root2.val:
7        return False
8    return (flipEquiv(root1.left, root2.left) and flipEquiv(root1.right, root2.right)) or (flipEquiv(root1.left, root2.right) and flipEquiv(root1.right, root2.left))

Complexity note: The time complexity is O(n) because we visit each node exactly once, and the space complexity is O(n) due to the recursion stack in the worst case.

  • 1Flipping a tree is similar to rearranging furniture; the same pieces can look different based on how they are arranged.
  • 2The problem can be approached recursively, leveraging the properties of binary trees.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.