Path Sum II
2015-06-03 11:58
344 查看
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
return
The path sum needs us to return a boolean whereas this problem wants us to return all the possible paths. Using DFS to list all the possible paths.
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] ]
The path sum needs us to return a boolean whereas this problem wants us to return all the possible paths. Using DFS to list all the possible paths.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> ret = new ArrayList<List<Integer>>(); if (root == null) return ret; List<Integer> list = new ArrayList<Integer>(); helper(root, sum, ret, list); return ret; } private void helper(TreeNode root, int sum, List<List<Integer>> ret, List<Integer> list) { if (root == null) return; if (root.val == sum && root.left == null && root.right == null) { list.add(root.val); ret.add(new ArrayList<Integer>(list)); } else { list.add(root.val); helper(root.left, sum - root.val, ret, list); helper(root.right, sum - root.val, ret, list); } list.remove(list.size() - 1); } }
相关文章推荐
- document.onmouseover事件的广泛性
- Step into Gradle - 01 - 基本使用
- ios 同步异步消息
- iOS 根据图片URL从本地相册获取图片
- jquery中添加属性和删除属性
- Python找出文件中使用率最高的汉字实例详解
- ndroid中Activity四种启动模式和taskAffinity属性详解
- 课程设计---约瑟夫环
- 021_04Fragment简单应用
- ListView的使用
- velocity 配置文件详解
- ArcGIS教程:区域填充
- 分享女性每月四个时期的保养重点
- struts2 jsp提交到action出现中文乱码问题
- 年薪十万可签订协议
- java个人学习笔记:多态
- 解决/usr/bin/ld: cannot find -lxxx
- 类与对象的创建详解(适合新人)
- 查看程序占用tomcat内存情况
- leetcode Pow(x, n)