Algorithm series-leetcode-34. The path summed to a certain value in the binary tree

Sword refers to Offer 34. The path that sums to a certain value in the binary tree (medium)

Given the root node of your binary tree rootand an integer target sum targetSum, find all paths from the root node to the leaf nodes whose sum equals the given target sum.

A leaf node is a node that has no child nodes.

Example 1:

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]]

Depth-first traversal

/**
 * 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;
};

Guess you like

Origin blog.csdn.net/animatecat/article/details/124463580