> ## Content Index
> Fetch the complete content index at: https://andybase.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# 951 Flip Equivalent Binary Trees
- URL: https://andybase.com/951-flip-equivalent-binary-trees/
- Published: 2018-12-06T22:14:39.000Z
- Updated: 2018-12-06T22:14:39.000Z
- Author: andy
- Tags: leetcode, contest, #Migrated-1784083136856, #wp, #wp-post, #Import 2026-07-15 02:38

Link: [https://leetcode.com/problems/flip-equivalent-binary-trees/ ](https://leetcode.com/problems/flip-equivalent-binary-trees/?ref=andybase.com)

## Thought

If 2 nodes are equivalent, either their left and right side match, or they are flipped match. So using a recursion(why recursion? It is a Tree!), and try to match each node pairs from root1 and root2.

For each recursion level, I will first compare if current node pair have the same value. (I can return False immediately if not match). If it matches, there are 3 cases:

1. They are identical -> recursion with (root1.left, root2.left,) and (root1.right, root2.right) should return True
2. They are flipped -> recursion with (root1.right, root2.left,) and (root1.left, root2.right) should return True
3. They are different -> Otherwise

## Code

```
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def flipEquiv(self, root1, root2):
        """
        :type root1: TreeNode
        :type root2: TreeNode
        :rtype: bool
        """
        def compare(node1,node2):
            if node1 == None and node2 == None:
                return True
            if node1 == None or node2 == None:
                return False
            if node1.val != node2.val:
                return False
            res = compare(node1.left, node2.left) and compare(node1.right, node2.right)
            res = res or compare(node1.left, node2.right) and compare(node1.right, node2.left)
            return res
        return compare(root1, root2)
```

## Runtime

Time: O(n)

Space: O(1)