本问题对应的 leetcode 原文链接:剑指 Offer 34. 二叉树中和为某一值的路径

问题描述

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

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

示例1 :

34

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

示例2 :

34-2

输入:root = [1,2,3], targetSum = 5
输出:[]

示例 3:

输入:root = [1,2], targetSum = 0
输出:[]
  • 提示:
    • 树中节点总数在范围 [0, 5000]
    • -1000 <= Node.val <= 1000
    • -1000 <= targetSum <= 1000

解题思路

视频讲解直达: 本题视频讲解

代码实现

class Solution {
    List<List<Integer>> res;
    List<Integer> tmp;
    public List<List<Integer>> pathSum(TreeNode root, int target) {
        res = new ArrayList<>();
        tmp = new ArrayList<>();
        dsf(root, target);
        return res;
    }
    void dsf(TreeNode root, int target){
        if(root == null){
            return;
        }

        tmp.add(root.val);
        target = target - root.val;
        if(root.left == null && root.right == null && target == 0){
            res.add(new ArrayList<>(tmp));
        }
        dsf(root.left, target);
        dsf(root.right, target);

        tmp.remove(tmp.size() - 1);

    }
}

时间复杂度:O(n)
空间复杂度:O(n)

Python

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def pathSum(self, root, target):
        """
        :type root: TreeNode
        :type target: int
        :rtype: List[List[int]]
        """
        res = []
        tmp = []
        def dsf(root, target):
            if not root:
                return
            tmp.append(root.val)
            target -= root.val
            if not root.left and not root.right and target == 0:
                res.append(tmp[:])
            dsf(root.left, target)
            dsf(root.right, target)
            tmp.pop()

        dsf(root, target)
        return res

C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int target) {
        vector<vector<int>> res;
        vector<int> tmp;
        function<void(TreeNode*, int)> dfs = [&](TreeNode* root, int target) {
            if (!root) {
                return;
            }
            tmp.push_back(root->val);
            target -= root->val;
            if (!root->left && !root->right && target == 0) {
                res.push_back(tmp);
            }
            dfs(root->left, target);
            dfs(root->right, target);
            tmp.pop_back();
        };

        dfs(root, target);
        return res;
    }
};

Go

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func pathSum(root *TreeNode, target int) [][]int {
    var res [][]int
    var tmp []int
    var dfs func(*TreeNode, int)
    dfs = func(root *TreeNode, target int) {
        if root == nil {
            return
        }
        tmp = append(tmp, root.Val)
        target -= root.Val
        if root.Left == nil && root.Right == nil && target == 0 {
            res = append(res, append([]int{}, tmp...))
        }
        dfs(root.Left, target)
        dfs(root.Right, target)
        tmp = tmp[:len(tmp)-1]
    }

    dfs(root, target)
    return res
}

JS

/**
 * @param {TreeNode} root
 * @param {number} target
 * @return {number[][]}
 */
var pathSum = function(root, target) {
  var res = [];
  var tmp = [];
  dsf(root, target);
  return res;

  function dsf(root, target) {
    if (root == null) {
      return;
    }

    tmp.push(root.val);
    target = target - root.val;
    if (root.left == null && root.right == null && target == 0) {
      res.push([...tmp]);
    }
    dsf(root.left, target);
    dsf(root.right, target);
    tmp.pop();
  }
};

发表回复

后才能评论