-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathInsufficient Nodes in Root to Leaf Paths.py
49 lines (45 loc) · 2.1 KB
/
Insufficient Nodes in Root to Leaf Paths.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 Solution:
"""
we can try to solve this problem using depth first traversal
"""
def dfs(self, root, sum_so_far, limit):
if root is None:
return None, 0
x, left = self.dfs(root.left, sum_so_far + root.val, limit)
y, right = self.dfs(root.right, sum_so_far + root.val, limit)
# print('for node= {}, sum_so_far= {}, left= {}, right= {}'.format(root.val, sum_so_far, left, right))
if root.left is None and root.right is None:
# it is leaf, left and right should be 0
if sum_so_far + root.val < limit:
# node is insufficient
return None, root.val
else:
# node is sufficient
return root, root.val
elif root.left is not None and root.right is None:
root.left = x
if sum_so_far + root.val + left < limit:
# node is insufficient
return None, root.val + left
else:
return root, root.val + left
elif root.left is None and root.right is not None:
root.right = y
if sum_so_far + root.val + right < limit:
return None, root.val + right
else:
return root, root.val + right
elif root.left is not None and root.right is not None:
root.left = x
root.right = y
if sum_so_far + root.val + left < limit and sum_so_far + root.val + right < limit:
return None, max(root.val + left, root.val + right)
elif sum_so_far + root.val + left < limit and sum_so_far + root.val + right > limit:
return root, root.val + right
elif sum_so_far + root.val + left > limit and sum_so_far + root.val + right < limit:
return root, root.val + left
else:
return root, max(root.val + left, root.val + right)
def sufficientSubset(self, root: Optional[TreeNode], limit: int) -> Optional[TreeNode]:
root, _ = self.dfs(root, 0, limit)
return root