-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcousins_in_binary_tree.py
36 lines (32 loc) · 1.12 KB
/
cousins_in_binary_tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from typing import Optional
from BinaryTree import TreeNode, BinaryTree
class Solution:
def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
"""
Trick used is forcefully adding a None as a separator between children of same parents
"""
if not root:
return False
queue = [root]
while(len(queue) != 0):
xx, yy = (-1, -1)
length = len(queue)
for i in range(0, length):
element = queue[i]
if not element:
continue
if element.val == x:
xx = i
if element.val == y:
yy = i
queue.append(element.left)
queue.append(element.right)
queue.append(None) #trick
queue = queue[length:]
if xx != -1 and yy != -1 and xx+1 != yy and yy+1 != xx:
return True
return False
solution = Solution()
root = BinaryTree().create_tree_from_array([10,1,2,3,4,5,6])
is_cousin = solution.isCousins(root, 4, 5)
print(is_cousin)