-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlist_cousins.py
65 lines (60 loc) · 1.72 KB
/
list_cousins.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
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
64
'''
List cousins - Daily Interview Problem
Given a binary tree and a given node value, return all of the node's cousins.
Two nodes are considered cousins if they are on the same level of the tree with different parents.
You can assume that all nodes will have their own unique value.
Example:
# 1
# / \
# 2 3
# / \ \
# 4 6 5
print list_cousins(root, 5)
# [4, 6]
'''
class Node(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def list_cousins(root, val):
if val == None or root == None:
return []
queue = [root]
parents = []
node_found = False
brother = None
while queue:
parents = queue
queue = []
for n in parents:
if n.left and n.left.val == val:
node_found = True
brother = n.right
if n.right and n.right.val == val:
node_found = True
brother = n.left
if n.left and n.left != brother and n.left.val != val:
queue.append(n.left)
if n.right and n.right != brother and n.right.val != val:
queue.append(n.right)
if node_found:
return [x.val for x in queue]
return []
# Test case
root = Node(1)
root.left = Node(2)
root.left.left = Node(4)
root.left.left.left = Node(10)
root.left.left.right = Node(11)
root.left.right = Node(6)
root.left.right.right = Node(13)
root.right = Node(3)
root.right.right = Node(5)
root.right.right.left = Node(23)
root.right.right.right = Node(7)
print list_cousins(root, 5)
print list_cousins(root, 4)
print list_cousins(root, 10)
print list_cousins(root, 13)
print list_cousins(root, 11)