LeetCode 113. Path Sum II

本文介绍了一种解决二叉树路径求和问题的方法,通过深度优先搜索(DFS)找到所有从根节点到叶子节点的路径,使得路径上的节点值之和等于给定的和值。详细解释了算法实现过程,包括使用ArrayList存储路径和处理引用问题,以及时间复杂度和空间复杂度分析。

原题链接在这里:https://leetcode.com/problems/path-sum-ii/

题目:

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]

题解:

Path Sum相似.

DFS, 终止条件是当遇到叶子节点时判断sum是否为0, 若是则res加当前item. 若root.left 不为空,左节点继续dfs, 用完后要remove掉尾节点, 右侧相同.

Note:1. 当res加item时一定要res.add(new ArrayList(item)), 因为list 是 pass by reference, 后面若更改item, 则已经加到res里的item也会同时更改。

2. 去掉list尾部就用list.remove(list.size()-1).

Time Complexity: O(n), 每个叶子节点都需要检查.

Space: O(nlogn), 一个item长度是logn, 最多可以有n/2组item, res大小是nlogn, n 是树总共的节点数. 用了logn层stack.

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public List<List<Integer>> pathSum(TreeNode root, int sum) {
12         List<List<Integer>> res = new ArrayList<List<Integer>>();
13         if(root == null){
14             return res;
15         }
16         
17         dfs(root, sum, new ArrayList<Integer>(), res);
18         return res;
19     }
20     
21     private void dfs(TreeNode root, int sum, List<Integer> item, List<List<Integer>> res){
22         sum -= root.val;
23         item.add(root.val);
24         
25         if(root.left == null && root.right == null && sum == 0){
26             res.add(new ArrayList<Integer>(item));
27             return;
28         }
29         if(root.left != null){
30             dfs(root.left, sum, item, res);
31             item.remove(item.size()-1);
32         }
33         if(root.right != null){
34             dfs(root.right, sum, item, res);
35             item.remove(item.size()-1);
36         }
37     }
38 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4824982.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值