博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Leetcode] Path Sum II
阅读量:4623 次
发布时间:2019-06-09

本文共 1330 字,大约阅读时间需要 4 分钟。

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

 

1 /** 2  * Definition for binary tree 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
> pathSum(TreeNode root, int sum) {12 List
> result=new ArrayList
>();13 List
tmp=new ArrayList
();14 dfs(result,tmp,sum,root,0);15 return result;16 }17 18 private void dfs(List
> result, List
tmp, int sum, TreeNode root, int curSum) {19 // TODO Auto-generated method stub20 if(root==null)21 return;22 if(root.left==null&&root.right==null){23 if(curSum+root.val==sum){24 tmp.add(root.val);25 result.add(new ArrayList
(tmp));26 tmp.remove(tmp.size()-1);27 return;28 }29 return;30 }31 tmp.add(root.val);32 dfs(result,tmp,sum,root.left,curSum+root.val);33 dfs(result,tmp,sum,root.right,curSum+root.val);34 tmp.remove(tmp.size()-1);35 }36 }

 

转载于:https://www.cnblogs.com/Phoebe815/p/4100942.html

你可能感兴趣的文章
用 query 方法 获得xml 节点的值
查看>>
Hello,Android
查看>>
Sublime Text 3 build 3103 注册码
查看>>
删与改
查看>>
SAP 中如何寻找增强
查看>>
spi驱动无法建立spidev问题
查看>>
ANDROID开发之SQLite详解
查看>>
如何依靠代码提高网络性能
查看>>
Zookeeper要安装在奇数个节点,但是为什么?
查看>>
discuz 微社区安装记录
查看>>
[BZOJ4824][Cqoi2017]老C的键盘 树形dp+组合数
查看>>
配置的热更新
查看>>
MySQL事务的开启与提交,autocommit自动提交功能
查看>>
PriorityQueue
查看>>
CODEVS1403 新三国争霸
查看>>
iOS 环信离线推送
查看>>
WPFTookit Chart 高级进阶
查看>>
雷云Razer Synapse2.0使用测评 -第二次作业
查看>>
django上传文件
查看>>
CVPR2013-papers
查看>>