codevn
235 天前
```
class TreeNode {
constructor(value = 0, children = []) {
this.value = value;
this.children = children;
}
}
function trimTree(root, target) {
if (!root) return null;
let queue = [root];
let result = new TreeNode(root.value);
let resultQueue = [result];
let currentSum = root.value;
while (queue.length > 0) {
let currentNode = queue.shift();
let resultNode = resultQueue.shift();
let childrenSum = 0;
let tempChildren = [];
for (let child of currentNode.children) {
queue.push(child);
childrenSum += child.value;
let newChild = new TreeNode(child.value);
tempChildren.push(newChild);
resultQueue.push(newChild);
}
if (currentSum + childrenSum <= target) {
resultNode.children = tempChildren;
currentSum += childrenSum;
} else {
let remaining = target - currentSum;
resultNode.children = [];
for (let child of tempChildren) {
if (child.value <= remaining) {
resultNode.children.push(child);
remaining -= child.value;
} else {
child.value = remaining;
resultNode.children.push(child);
break;
}
}
break;
}
}
return result;
}
// 示例
let child1 = new TreeNode(80);
let child2 = new TreeNode(80);
let root = new TreeNode(100, [child1, child2]);
let trimmedTree = trimTree(root, 200);
console.log(trimmedTree);
```
这意思么?