题目地址(113. 路径总和 II)
https://leetcode-cn.com/problems/path-sum-ii/
题目描述
给你二叉树的根节点 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]]示例 2:输入:root = [1,2,3], targetSum = 5输出:[]示例 3:输入:root = [1,2], targetSum = 0输出:[]提示:树中节点总数在范围 [0, 5000] 内-1000 <= Node.val <= 1000-1000 <= targetSum <= 1000
前置知识
公司
- 暂无
思路
关键点
代码
- 语言支持:Java
Java Code:
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/class Solution {public List<List<Integer>> pathSum(TreeNode root, int targetSum) {//返回值List<List<Integer>> res = new ArrayList<>();//节点判空if (root == null) {return res;}//节点路径List<Integer> path = new LinkedList<>();loop(root, targetSum, res, path);return res;}public void loop(TreeNode root,int targetSum,List<List<Integer>> res,List<Integer> path) {//进入递归循环就将root节点的值添加到路径中path.add(root.val);//递归到了叶子节点 判断给定值减去当前的节点值是否=0 如果=就将整个路径加到res中 然后返回 如果不等于就直接返回if (root.left == null && root.right == null) {if (targetSum - root.val == 0) {//注意这里不要直接加pathres.add(new ArrayList<>(path));}return;}//递归调用左节点if (root.left != null) {loop(root.left, targetSum-root.val , res, path);//回溯 调用完左节点后执行 目的是将递归过的节点的值从路径中移除path.remove(path.size() - 1);}//递归调用左节点if (root.right != null) {loop(root.right, targetSum-root.val , res, path);path.remove(path.size() - 1);}}}
复杂度分析
令 n 为数组长度。
- 时间复杂度:
#card=math&code=O%28n%29&id=wXRrT)
- 空间复杂度:
#card=math&code=O%28n%29&id=jSgrw)
