-
Notifications
You must be signed in to change notification settings - Fork 2
/
BST Downward Traversal.py
41 lines (33 loc) · 1.05 KB
/
BST Downward Traversal.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
'''
class Node:
def __init__(self,val):
self.data=val
self.left=None
self.right=None
'''
class Solution:
def verticallyDownBST(self, root, target):
def down(node, direction):
nonlocal res
if node:
if direction == 0:
res += node.data
down(node.left, direction-1)
down(node.right, direction+1)
def find(node, target):
nonlocal target_node
if target_node == None:
if node:
if node.data > target:
find(node.left, target)
elif node.data < target:
find(node.right, target)
else:
target_node = node
down(node, 0)
res = -target
target_node = None
find(root, target)
if res == -target:
return -1
return res