[leetcode]113. Path Sum II@Java解题报告

来源:互联网 发布:hbo 知乎 编辑:程序博客网 时间:2024/06/05 12:42

https://leetcode.com/problems/path-sum-ii/description/


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




package go.jacob.day808;import java.util.ArrayList;import java.util.List;/** * 解法类似Path sum。多了保存结果的操作 * @author Jacob * */public class Demo3 {//res保存结果List<List<Integer>> res ;public List<List<Integer>> pathSum(TreeNode root, int sum) {res = new ArrayList<List<Integer>>();if (root == null)return res;List<Integer> list=new ArrayList<Integer>();getPath(list,root,sum);return res;}private void getPath(List<Integer> list,TreeNode root, int sum) {if(root==null)return;list.add(root.val);if(root.val==sum&&root.left==null&&root.right==null)res.add(new ArrayList<Integer>(list));getPath(list,root.left,sum-root.val);getPath(list,root.right,sum-root.val);//移除最后一个元素list.remove(list.size()-1);}}


原创粉丝点击