本文由 简悦 SimpRead 转码, 原文地址 leetcode.cn
给你二叉树的根节点 root
和一个整数 limit
,请你同时删除树中所有 不足节点 ,并返回最终二叉树的根节点。 假如通过节点 node
的每种可能的 “根 - 叶” 路径上值的总和全都小于给定的 limit
,则该节点被称之为 不足节点 ,需要被删除。 叶子节点,就是没有子节点的节点。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* sufficientSubset(TreeNode* root, int limit) {
limit -= root->val;
if(root->left == root->right) {
return limit > 0? nullptr:root;
}
if (root->left) root->left = sufficientSubset(root->left,limit);
if(root->right) root->right = sufficientSubset(root->right, limit);
return root->left || root->right ? root : nullptr;
}
};
func sufficientSubset(root *TreeNode, limit int) *TreeNode {
if root == nil {
return nil
}
limit -= root.Val
if root.Left == root.Right { // root 是叶子
if limit > 0 { // 从根到叶子的路径和小于 limit,删除叶子
return nil
}
return root // 否则不删除
}
root.Left = sufficientSubset(root.Left, limit)
root.Right = sufficientSubset(root.Right, limit)
if root.Left == nil && root.Right == nil { // 如果儿子都被删除,就删 root
return nil
}
return root // 否则不删 root
}