1080. 根到叶路径上的不足节点

给定一棵二叉树的根 root,请你考虑它所有 从根到叶的路径:从根到任何叶的路径。(所谓一个叶子节点,就是一个没有子节点的节点)

假如通过节点 node 的每种可能的 “根-叶” 路径上值的总和全都小于给定的 limit,则该节点被称之为「不足节点」,需要被删除。

请你删除所有不足节点,并返回生成的二叉树的根。

链接

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
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} limit
* @return {TreeNode}
*/
var sufficientSubset = function(root, limit) {
if (root === null) return null

if (root.left === null && root.right === null) {
if (root.val < limit) {
return null
}
return root
}

limit -= root.val
root.left = sufficientSubset(root.left, limit)
root.right = sufficientSubset(root.right, limit)

if (root.left == null && root.right === null) {
return null
}

return root
};