[Leetcode]113. Path Sum II 求路径和一个数的所有路径
来源:互联网 发布:mac系统用windows软件 编辑:程序博客网 时间:2024/05/01 11:29
题目:
题意:给定一个二叉树,和一个整数,求二叉树中所有从根节点到叶子节点的路径和等于这个整数的路径。
代码实现:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { List<List<Integer>> result = new ArrayList<>(); public List<List<Integer>> pathSum(TreeNode root, int sum) { if(root == null){ return result; } ArrayList<Integer> list = new ArrayList<>(); myPathSum(root, sum, 0, list); return result; } public void myPathSum(TreeNode root, int sum, int current_sum, ArrayList<Integer> list) { list.add(root.val); current_sum += root.val; if (current_sum == sum && root.left == null && root.right == null) { result.add(new ArrayList<>(list)); return; } if (root.left != null) { myPathSum(root.left, sum, current_sum, new ArrayList<>(list)); } if (root.right != null) { myPathSum(root.right, sum, current_sum, new ArrayList<>(list)); } }}
代码中要注意的问题:1.左右子树递归的时候 要使用
new ArrayList<>(list)
而不是使用list, 使用list最后会多加结点
0 0
- [Leetcode]113. Path Sum II 求路径和一个数的所有路径
- [LeetCode]113. Path Sum II(列出二叉树根到叶路径和等于sum的所有路径)
- LeetCode Path Sum II路径和II
- Path Sum II 二叉树路径和,打印所有路径 @LeetCode
- LeetCode 113. Path Sum II(路径和)
- leetcode 113. Path Sum II-路径和|回溯算法
- Leetcode 113. Path Sum II 路径和2 解题报告
- Tree-----找出和等于给定数字的所有路径(113. Path Sum II)
- LeetCode | Path Sum II(路径和2)
- LeetCode OJ 之 Path Sum II (路径和 - 二)
- LeetCode Path Sum 路径和
- [LeetCode] 路径和 Path Sum
- leetcode Path Sum 路径和
- Path Sum II 路径和II
- [LeetCode]437. Path Sum III(求二叉树中路径和等于sum的数量)
- LeetCode OJ 之 Path Sum(求路径和)
- 【leetcode 二叉树路径和】Path Sum 和 Path Sum II
- 【二叉树】DFS计算路径和,保存路径【113. Path Sum II】【112. Path Sum】
- Java反射机制详解
- iOS FMDB的使用
- IO模型及select、poll、epoll和kqueue的区别
- Java 泛型
- npm
- [Leetcode]113. Path Sum II 求路径和一个数的所有路径
- datePicker时间控件最大日期、最小日期设置
- Jquery 在ios上事件委托失效?
- iframe跨域自适应高度
- Android 电量优化
- spring配置文件详解
- 解决php It is not safe to rely on the system's timezone settings. You are *required* to use the date.
- [Leetcode] 230. Kth Smallest Element in a BST
- springMVC参数绑定注解