LeetCode-113. Path Sum II

问题描述

Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.

A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.

Example :

img

1
2
3
4
5
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
Output: [[5,4,11,2],[5,8,4,5]]
Explanation: There are two paths whose sum equals targetSum:
5 + 4 + 11 + 2 = 22
5 + 8 + 4 + 5 = 22

Constraints:

  • The number of nodes in the tree is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000

解答

方法一:DFS迭代写法
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
* @Description: 113. Path Sum II
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* 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)
* }
*/
/**
* @description: DFS迭代写法
* @param {TreeNode} root
* @param {number} targetSum
* @return {number[][]}
*/
const pathSum = function(root, targetSum) {
if (!root) {
return []
}
let res = []
let nodeStack = [root]
let valStack = [root.val]
let pathStack = [[root.val]]

while (nodeStack.length) {
let cur = nodeStack.pop()
let curVal = valStack.pop()
// 当前节点经过的路径
let curPath = pathStack.pop()

if (cur.left === null && cur.right === null && curVal === targetSum) {
res.push(curPath)
}
if (cur.left) {
let leftPath = curPath.slice(0)
leftPath.push(cur.left.val)
pathStack.push(leftPath)
nodeStack.push(cur.left)
valStack.push(curVal + cur.left.val)
}
if (cur.right) {
let rightPath = curPath.slice(0)
rightPath.push(cur.right.val)
pathStack.push(rightPath)
nodeStack.push(cur.right)
valStack.push(curVal + cur.right.val)
}
}
return res
}
方法二:DFS递归写法
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
34
35
36
37
38
39
40
/*
* @Description: 113. Path Sum II
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* 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)
* }
*/
/**
* @description: DFS递归写法
* @param {TreeNode} root
* @param {number} targetSum
* @return {number[][]}
*/
const pathSum = function(root, targetSum) {
let res = []
let path = []

const dfs = (cur, curSum) => {
if (!cur) {
return
}
path.push(cur.val)
curSum -= cur.val
if (cur.left === null && cur.right === null && curSum === 0) {
res.push(path.slice(0))
}
dfs(cur.left, curSum)
dfs(cur.right, curSum)
path.pop()
}

dfs(root, targetSum)
return res
}