-
Notifications
You must be signed in to change notification settings - Fork 0
/
print_nodes_at_dist_k.py
49 lines (34 loc) · 969 Bytes
/
print_nodes_at_dist_k.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
class Node:
def __init__(self, data):
self.data = data
self.lc = None
self.rc = None
def printKDistanceNodeDown(root, dist):
if not root:
return
if dist == 0:
print(root.data)
return
printKDistanceNodeDown(root.lc, dist - 1)
printKDistanceNodeDown(root.rc, dist - 1)
def printKDistanceNode(root, target, k):
if not root:
return -1
if root == target:
printKDistanceNodeDown(target, k)
return 0 # couldn't we return 1 here??
dl = printKDistanceNode(root.lc, target, k)
if dl != -1:
if dl + 1 == k:
print(root.data)
else:
printKDistanceNodeDown(k - dl - 2)
return dl + 1
dr = printKDistanceNode(root.rc, target, k)
if dr != -1:
if dr + 1 == k:
print(root.data)
else:
printKDistanceNodeDown(k - dr - 2)
return dr + 1
return -1