当前位置:网站首页>[Binary Tree] Path Sum II
[Binary Tree] Path Sum II
2022-08-01 14:04:00 【Don't write blog is not great】
路径总和II
这道题目10分钟就可以完成了,I've gotten a lot out of practice lately,加油
路径总和,Divide into left and right subtrees,要注意的是JavaThe path needs to be additionally saved here,Otherwise, save directlypath都是null
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */
class Solution {
private List<List<Integer>> ret = new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
if(root == null) return ret;
List<Integer> path = new ArrayList<>();
searchPath(root, targetSum, path);
return ret;
}
private void searchPath(TreeNode root, int targetSum, List<Integer> path){
if(root == null) return;
if(root.left == null && root.right == null){
if(root.val == targetSum){
List<Integer> ans = new ArrayList<>();
for(int i = 0; i < path.size(); i++){
ans.add(path.get(i));
}
ans.add(root.val);
ret.add(ans);
}
}
path.add(root.val);
searchPath(root.left, targetSum-root.val, path);
searchPath(root.right, targetSum-root.val, path);
path.remove(path.size()-1);
}
}
边栏推荐
猜你喜欢
随机推荐
gpio模拟串口通信
程序员的浪漫七夕
易优压双驱挖掘机压路机器类网站源码 v1.5.8
8. How does the SAP ABAP OData service support the Create operation
高仿项目协作工具【Worktile】,从零带你一步步实现组织架构、网盘、消息、项目、审批等功能
如何降低Istio服务网格中Envoy的内存开销
立新能源深交所上市:市值55亿 哈密国投与国有基金是股东
沃文特生物IPO过会:年营收4.8亿 养老基金是股东
Qt实战案例(56)——利用QProcess实现应用程序重启功能
2022-07-29 网工进阶(二十二)BGP-其他特性(路由过滤、团体属性、认证、AS欺骗、对等体组、子路由器、路由最大接收数量)
PyTorch 进阶之路:在 GPU 上训练深度神经网络
kubernetes之DaemonSet以及滚动更新
MCU开发是什么?国内MCU产业现状如何
从零开始Blazor Server(4)--登录系统
【无标题】
2022图片在线加水印源码
Data Mining-04
tensorflow2.0手写数字识别(tensorflow手写体识别)
牛客刷SQL--5
荣信文化通过注册:年营收3.8亿 王艺桦夫妇为实控人