5084. Insufficient Nodes in Root to Leaf Paths

65 篇文章 0 订阅
23 篇文章 0 订阅

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.)

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:

  1. The given tree will have between 1 and 5000 nodes.
  2. -10^5 <= node.val <= 10^5
  3. -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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值