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
63 lines (44 loc) · 1.15 KB
/
check_cousin.py
File metadata and controls
63 lines (44 loc) · 1.15 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
"""
Check if two nodes are cousin or not
Condition for being cousin -
1. Level is same
2. They are not siblings
"""
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 not root:
return False
return (root.left == a and root.right == b) or \
(root.right == b and root.left == 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
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.left.right.right = Node(15)
root.right.left = Node(6)
root.right.right = Node(7)
root.right.left.right = Node(8)
node1 = root.left.right
node2 = root.right.right
print(is_cousin(root, node1, node2))