算法系列-leetcode-34.二叉树中和为某一值的路径

剑指 Offer 34. 二叉树中和为某一值的路径(中等)

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

叶子节点 是指没有子节点的节点。

示例 1:

输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:[[5,4,11,2],[5,8,4,5]]

深度优先遍历

/**
 * 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) {
    let res=[]
  function dfs (root, path, sum){
    if (root == null) return null;
    path.push(root.val);
    // 路径中加入当前节点的值
    sum += root.val;
    // 到了叶子节点 并且 整个路径的值的和 和target相等,则推入结果集中
    if (root.left == null && root.right == null && target == sum)
      res.push(path.slice());
    // 递归的去左右子树当中查找路径
    dfs(root.left, path, sum);
    dfs(root.right, path, sum);
    sum -= root.val;
    path.pop();
  };
  dfs(root, [], 0);
  return res;
};

猜你喜欢

转载自blog.csdn.net/animatecat/article/details/124463580