This commit is contained in:
parent
bf2f9a145f
commit
c5dfcc54f3
1 changed files with 35 additions and 0 deletions
35
medium/flip_equivalent_binary_trees.py
Normal file
35
medium/flip_equivalent_binary_trees.py
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
from typing import Optional
|
||||
|
||||
# https://leetcode.com/problems/flip-equivalent-binary-trees
|
||||
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 == None and root2 == None:
|
||||
return True
|
||||
if root1 == None or root2 == None:
|
||||
return False
|
||||
if root1.val != root2.val:
|
||||
return False
|
||||
flip = False
|
||||
if (
|
||||
(root1.left == None and root2.right == None) or \
|
||||
(root1.left != None and root2.right != None and \
|
||||
root1.left.val == root2.right.val)
|
||||
) and \
|
||||
(
|
||||
(root1.right == None and root2.left == None) or \
|
||||
(root1.right != None and root2.left != None and \
|
||||
root1.right.val == root2.left.val)
|
||||
):
|
||||
flip = True
|
||||
if flip:
|
||||
tmp = root2.left
|
||||
root2.left = root2.right
|
||||
root2.right = tmp
|
||||
return self.flipEquiv(root1.left, root2.left) and \
|
||||
self.flipEquiv(root1.right, root2.right)
|
||||
Loading…
Add table
Add a link
Reference in a new issue