- Notifications
You must be signed in to change notification settings - Fork 625
/
Copy path1080.py
68 lines (44 loc) · 1.67 KB
/
1080.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
65
66
67
68
'''
Given the root of a binary tree, consider all root to leaf paths: paths from the root to any leaf. (A leaf is a node with no children.)
A node is insufficient if every such root to leaf path intersecting this node has sum strictly less than limit.
Delete all insufficient nodes simultaneously, and return the root of the resulting binary tree.
Example 1:
Input: root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1
Output: [1,2,3,4,null,null,7,8,9,null,14]
Example 2:
Input: root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22
Output: [5,4,8,11,null,17,4,7,null,null,null,5]
Example 3:
Input: root = [1,2,-3,-5,null,4,null], limit = -1
Output: [1,null,-3,4]
Note:
The given tree will have between 1 and 5000 nodes.
-10^5 <= node.val <= 10^5
-10^9 <= limit <= 10^9
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
classSolution(object):
defsufficientSubset(self, root, limit):
"""
:type root: TreeNode
:type limit: int
:rtype: TreeNode
"""
defreduce_tree(root, limit, curr_sum):
ifnotroot:
returnNone
l_sum= [curr_sum[0] +root.val]
r_sum= [l_sum[0]]
root.left=reduce_tree(root.left, limit, l_sum)
root.right=reduce_tree(root.right, limit, r_sum)
curr_sum[0] =max(l_sum[0], r_sum[0])
ifcurr_sum[0] <limit:
root=None
returnroot
curr_sum= [0]
returnreduce_tree(root, limit, curr_sum)