二叉树的路径和
来源:互联网 发布:淘宝仿货做的很好的店 编辑:程序博客网 时间:2024/06/05 23:39
给定一个二叉树,找出所有路径中各节点相加总和等于给定 目标值
的路径。
一个有效的路径,指的是从根节点到叶节点的路径。
样例
给定一个二叉树,和 目标值 = 5
:
1 / \ 2 4 / \ 2 3
返回:
[ [1, 2, 2], [1, 4]]
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root the root of binary tree
* @param target an integer
* @return all valid paths
*/
public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) {
// Write your code here
return dfs(root,new ArrayList<Integer>(),0,new ArrayList<List<Integer>>(),target);
}
public List<List<Integer>> dfs(TreeNode root,List<Integer> node, int sum, List<List<Integer>> paths,int target)
{
if(root==null)
{
return new ArrayList<List<Integer>>();
}
List<List<Integer>> path=new ArrayList<List<Integer>>();
if(root.left!=null)
{
List<Integer> nodes=new ArrayList<Integer>();
if(node!=null)
{
nodes.addAll(node);
}
nodes.add(root.val);
List<List<Integer>> temp=dfs(root.left,nodes,sum+root.val,paths,target);
if(temp!=null)
{
path.addAll(temp);
}
}
if(root.right!=null)
{
List<Integer> nodes=new ArrayList<Integer>();
if(node!=null)
{
nodes.addAll(node);
}
nodes.add(root.val);
List<List<Integer>> temp=dfs(root.right,nodes,sum+root.val,paths,target);
if(temp!=null)
{
path.addAll(temp);
}
}
if(root.left==null&&root.right==null)
{
List<Integer> nodes=new ArrayList<Integer>();
if(node!=null)
{
nodes.addAll(node);
}
nodes.add(root.val);
if(sum+root.val==target)
{
path.add(nodes);
}
else{
path=new ArrayList<List<Integer>>();
}
}
return path;
}
}
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- 二叉树的路径和
- mysqldiff使用
- How to Turn On “About This Page” in Oracle R12 OAF Pages
- spring 常用
- java基础:面向对象(继承中构造方法的注意事项)
- Spring MVC 入门指南(一):HelloWorld
- 二叉树的路径和
- 算法基础-->贪心和动态规划
- poj2229 Sumsets(dp)
- python 使用mysqldb模块通过SSHTunnelForwarder隧道连接mysql
- leetcode 650. 2 Keys Keyboard
- windows查看端口占用以及关闭相应的进程
- Spring MVC 入门指南(二):@RequestMapping用法详解
- 1062. 最简分数(20)
- 回收站功能实现