题目
- 输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
- leetcode链接:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/
思路
- 前序遍历
代码
/**
* 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} target
* @return {number[][]}
*/
var pathSum = function (root, target) {
const result = []
function order(node, sum, path) {
if (!node) return
const currentSum = node.val + sum
const currentPath = [...path, node.val]
if (currentSum === target && !node.left && !node.right) {
result.push([...currentPath])
return
}
order(node.left, currentSum, currentPath)
order(node.right, currentSum, currentPath)
}
order(root, 0, [])
return result
}