5084. Insufficient Nodes in Root to Leaf Paths

5084. Insufficient Nodes in Root to Leaf Paths

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:

  1. The given tree will have between 1 and 5000 nodes.
  2. -10^5 <= node.val <= 10^5
  3. -10^9 <= limit <= 10^9

方法1:

思路:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* sufficientSubset(TreeNode* root, int limit) {
        if (!root) return nullptr;
        if (!root -> left && !root -> right){
            if  (root -> val < limit) return nullptr;
            else return root;
        }
        
        auto lret = sufficientSubset(root -> left, limit - root -> val);
        auto rret = sufficientSubset(root -> right, limit - root -> val);
        
        if (!lret && !rret) return nullptr;
        else{ root -> left = lret; root -> right = rret; }
        
        return root;
    }
};
class Solution {
public:
    TreeNode* sufficientSubset(TreeNode* root, int limit) {
        if (suffHelper(root, limit)) return root;
        return nullptr;
    }
    
    bool suffHelper(TreeNode * root, int limit) {
        if (!root) return false;
        // 当有一边是null的时候,不应该阻止root被砍
        // if (!root) return true;
        if (!root -> left && !root -> right){
            if  (root -> val < limit) return false;
            else return true;
        }
        
        bool lret = sufficientSubset(root -> left, limit - root -> val);
        bool rret = sufficientSubset(root -> right, limit - root -> val);
        
        if (!lret) root -> left = nullptr;
        if (!rret) root -> right = nullptr;
        
        return lret || rret;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值