For a binary tree T, we can define a flip operation as follows:
choose any node, and swap the left and right child subtrees.
A binary tree X is flip equivalent to a binary tree Y if and only
if we can make X equal to Y after some number of flip operations.
Given the roots of two binary trees root1 and root2,
return true if the two trees are flip equivalent or false otherwise.
1, 3, 5 번 노드에 각각 뒤집기를 실행해 같게 만들수 있다.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
# 둘다 없으면 괜찮다.
if root1 is None and root2 is None:
return True
# 둘중 하나만 있으면 안됨
if root1 is None or root2 is None:
return False
# 값이 달라도 안됨
if root1.val != root2.val:
return False
# 자식을 나열하고 값으로 정렬, None은 특이 케이스로 -1
root1childs = [root1.left, root1.right]
root2childs = [root2.left, root2.right]
root1childs.sort(key=lambda k: -1 if k is None else k.val)
root2childs.sort(key=lambda k: -1 if k is None else k.val)
# 정렬 후 재귀
left = self.flipEquiv(root1childs[0], root2childs[0])
right = self.flipEquiv(root1childs[1], root2childs[1])
return left and right