leetcode-113. 路径总和 II
题目描述
给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
叶子节点 是指没有子节点的节点。
运行结果
代码如下
class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = val === undefined ? 0 : val;
this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right;
}
}
function pathSum(root: TreeNode | null, targetSum: number): number[][] {
const res = [];
let temp = [];
function getPath(root: TreeNode | null, sum = 0) {
if (!root) return;
sum += root.val;
temp.push(root.val);
if (sum === targetSum && !root.left && !root.right) {
res.push([...temp]);
return;
}
if (root.left) {
getPath(root.left, sum);
temp.pop();
}
if (root.right) {
getPath(root.right, sum);
temp.pop();
}
}
getPath(root);
return res;
}
const res = pathSum(tree, 22);
debugger;
工具函数
const nodes = [5, 4, 8, 11, null, 13, 4, 7, 2, null, null, 5, 1];
function toTree(nodes: number[]) {
if (!nodes.length) return null;
const root = new TreeNode(nodes[0]);
let p = [root];
let t = [];
let i = 1;
while (i < nodes.length) {
for (let j = 0; j < p.length; j++) {
if (p[j]) {
nodes[i] !== null ? (p[j].left = new TreeNode(nodes[i++])) : i++;
nodes[i] !== null ? (p[j].right = new TreeNode(nodes[i++])) : i++;
t.push(p[j].left);
t.push(p[j].right);
} else {
t.push(null);
t.push(null);
// i += 2;
}
}
p = t;
t = [];
}
return root;
}
const tree = toTree(nodes);