Skip to content

Commit 742227f

Browse files
951 Flip Equivalent Binary Trees.py
1 parent 416dbad commit 742227f

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

951 Flip Equivalent Binary Trees.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
#!/usr/bin/python3
2+
"""
3+
For a binary tree T, we can define a flip operation as follows: choose any node,
4+
and swap the left and right child subtrees.
5+
6+
A binary tree X is flip equivalent to a binary tree Y if and only if we can make
7+
X equal to Y after some number of flip operations.
8+
9+
Write a function that determines whether two binary trees are flip equivalent.
10+
The trees are given by root nodes root1 and root2.
11+
12+
13+
14+
Example 1:
15+
16+
Input: root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7]
17+
Output: true
18+
Explanation: We flipped at nodes with values 1, 3, and 5.
19+
Flipped Trees Diagram
20+
21+
22+
Note:
23+
24+
Each tree will have at most 100 nodes.
25+
Each value in each tree will be a unique integer in the range [0, 99].
26+
"""
27+
28+
# Definition for a binary tree node.
29+
class TreeNode:
30+
def __init__(self, x):
31+
self.val = x
32+
self.left = None
33+
self.right = None
34+
35+
36+
class Solution:
37+
def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool:
38+
"""
39+
O(N)
40+
"""
41+
if not root1 and not root2:
42+
return True
43+
elif not root1 or not root2:
44+
return False
45+
46+
if root1.val != root2.val:
47+
return False
48+
49+
return self.flipEquiv(root1.left, root2.left) and self.flipEquiv(root1.right, root2.right) or \
50+
self.flipEquiv(root1.left, root2.right) and self.flipEquiv(root1.right, root2.left)

0 commit comments

Comments
 (0)