Link: https://leetcode.com/problems/flip-equivalent-binary-trees/
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:
- They are identical -> recursion with (root1.left, root2.left,) and (root1.right, root2.right) should return True
- They are flipped -> recursion with (root1.right, root2.left,) and (root1.left, root2.right) should return True
- 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)