题目
输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。二叉树节点的定义如下:
function TreeNode(val, left, right) {
this.val = (val===undefined ? 0 : val)
this.left = (left===undefined ? null : left)
this.right = (right===undefined ? null : right)
}
示例
10
/ \
5 12
/ \
4 7
输入:root = [10, 5, 12, 4, 7, null, null], targetSum = 22
输出:[[10, 5, 7], [10, 22]]
提示:
- 树中节点总数在范围 [0, 5000] 内
- -1000 <= Node.val <= 1000
- -1000 <= targetSum <= 1000
题解
深度优先
/**
* 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} targetSum
* @return {number[][]}
*/
var pathSum = function(root, targetSum) {
const res = [];
const path = [];
dfs(root, targetSum, path, res);
return res;
};
var dfs = (root, targetSum, path, res) => {
if (root == null) {
return;
}
path.push(root.val);
targetSum -= root.val;
if (root.left === null && root.right === null && targetSum === 0) {
res.push([...path]);
}
dfs(root.left, targetSum, path, res);
dfs(root.right, targetSum, path, res);
path.pop();
}
复杂度分析
- 时间复杂度:O(N^2),其中 NNN 是树的节点数。在最坏情况下,树的上半部分为链状,下半部分为完全二叉树,并且从根节点到每一个叶子节点的路径都符合题目要求。此时,路径的数目为 O(N),并且每一条路径的节点个数也为 O(N),因此要将这些路径全部添加进答案中,时间复杂度为 O(N^2)。
- 空间复杂度:O(N),其中 NNN 是树的节点数。空间复杂度主要取决于栈空间的开销,栈中的元素个数不会超过树的节点数。
引用
- 剑指offer书籍
- 力扣题解