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]
Note:
- The given tree will have between
1
and5000
nodes. -10^5 <= node.val <= 10^5
-10^9 <= limit <= 10^9
思路:很无语,题目本身说法错了,leaf应该是没有left,right node的,但是题目OJ判的时候是at most 1 child??
anyway,比赛的时候代码如下,先遍历一遍求出经过每个node的path的sum的最大值,每次到了leaf,update改路径上的最大值
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def sufficientSubset(self, root, limit):
"""
:type root: TreeNode
:type limit: int
:rtype: TreeNode
"""
d={}
p=[]
loc={}
def dfs(r,su, pa,left):
loc[r]=(pa,left)
if not r.left and not r.right:
p.append(r)
for s in p:
if s in d: d[s]=max(d[s],su+r.val)
else: d[s]=su+r.val
p.pop()
return
if r.left:
p.append(r)
dfs(r.left,su+r.val, r,True)
p.pop()
if r.right:
p.append(r)
dfs(r.right,su+r.val, r,False)
p.pop()
dfs(root,0, None,True)
print(min(d.values()), max(d.values()))
for s in d:
if d[s]<limit:
if s==root: return None
p,left=loc[s]
if left: p.left=None
else: p.right=None
return root
不过似乎有更加easy的solution,tree之类的问题不就是递归么?套路忘得差不多了....
def sufficientSubset(self, root, limit):
if root.left == root.right is None:
return None if root.val < limit else root
if root.left:
root.left = self.sufficientSubset(root.left, limit - root.val)
if root.right:
root.right = self.sufficientSubset(root.right, limit - root.val)
return root if root.left or root.right else None