forked from prabhupant/python-ds
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck_cousin.py
More file actions
36 lines (24 loc) · 766 Bytes
/
check_cousin.py
File metadata and controls
36 lines (24 loc) · 766 Bytes
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
# Check if two nodes are cousin or not
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def level(root, node, lev):
if not root:
return 0
if root == node:
return lev
l = level(root.left, node, lev + 1)
if not l == 0:
return l
l = level(root.right, node, lev + 1)
def is_sibling(root, a, b):
if root is None:
return 0
return ( (root.left == a and root.right == b) or (root.left == b and root.right == a) or is_sibling(root.left, a, b) or is_sibling(root.right, a, b) )
def is_cousin(root, a, b):
if level(root, a, 1) == level(root, b, 1) and not is_sibling(root, a, b):
return True
else:
return False