专栏中心

EEPW首页 > 专栏 > Java视频教程之LeetCode--Path Sum III分析及实现方法分享

Java视频教程之LeetCode--Path Sum III分析及实现方法分享

发布人:扣丁学堂1 时间:2021-01-07 来源:工程师 发布文章

废话不多说了,下面和大家分享一下扣丁学堂Java在线学习课程:LeetCode -- Path Sum III分析及实现方法,希望可以帮到对Java开发感兴趣的小伙伴们。

Java在线学习课程:LeetCode -- Path Sum III分析及实现方法

LeetCode -- Path Sum III分析及实现方法

题目描述:

You are given a binary tree in which each node contains an integer value.


Find the number of paths that sum to a given value.


The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).


The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

给定一个二叉树,遍历过程中收集所有可能路径的和,找出和等于X的路径树。


思路:

设当前节点为root,分别收集左右节点路径和的集合,merge到当前集合中;

将当前节点添加到数组中,构成新的可能路径。


实现代码:

/** 
 * Definition for a binary tree node. 
 * public class TreeNode { 
 * public int val; 
 * public TreeNode left; 
 * public TreeNode right; 
 * public TreeNode(int x) { val = x; } 
 * } 
 */ 
public class Solution { 
 
 private int _sum; 
 private int _count; 
 public int PathSum(TreeNode root, int sum) 
 { 
 _count = 0; 
 _sum = sum; 
 Travel(root, new List<int>()); 
 return _count; 
 } 
 
 private void Travel(TreeNode current, List<int> ret){ 
 if(current == null){ 
  return ; 
 } 
  
 if(current.val == _sum){ 
  _count ++; 
 } 
  
 var left = new List<int>(); 
 Travel(current.left, left); 
  
 var right = new List<int>(); 
 Travel(current.right, right); 
  
 ret.AddRange(left); 
 ret.AddRange(right); 
  
 for(var i = 0;i < ret.Count; i++){ 
  ret[i] += current.val; 
  if(ret[i] == _sum){ 
  _count ++; 
  } 
 } 
 ret.Add(current.val); 
  
 //Console.WriteLine(ret); 
 } 
}


好了,以上就是小编给大家分享的Java在线学习课程:LeetCode -- Path Sum III分析及实现方法,想要学好Java开发的小伙伴一定要选择专业的Java培训机构,小编给大家推荐专业的Java培训机构扣丁学堂,扣丁学堂不仅有专业的老师和与时俱进的课程体系还有大量的Java在线教程供学员观看学习,心动的小伙伴快快行动吧。扣丁学堂java技术交流群:487098661。微信号:codingbb

专栏文章内容及配图由作者撰写发布,仅供工程师学习之用,如有侵权或者其他违规问题,请联系本站处理。 联系我们

关键词:

相关推荐

INA219功率监测+OLED显示

AS6221EvalKit:精度最高的数字温度传感器开发使用

ADI公司DiffAmpCalc导览

视频 2012-06-18

数字电压表设计教程之模数转换原理分析

新突破!100Tops机器人算力芯片如何实现高效散热与性能平衡?

ADI在线研讨会:利用 ECG AFE 简化病人监护仪设计

视频 2012-06-18

台积电3nm与5nm产能满载

EDA/PCB 2025-09-28

使用Tensorflow训练模型并且部署到ESP32S3进行推理

南芯科技发布车规级高端MCU PMIC

在FireBeetle2ESP32P4开发板上使用ESP-IDF组件方式读取SHT30温湿度传感器

基于AD855X的压力变送器的校准系统

视频 2012-06-20

艾迈斯欧司朗推出高可靠性电容式传感,直面汽车应用严苛工况挑战

ADI在线研讨会:解决工业自动化领域的隔离难题

视频 2012-06-18

如何申请ADI免费样片

视频 2012-06-18

[求助]

kanyi305 2005-06-17

KG+GNN的BYOM部署流程

更多 培训课堂
更多 焦点
更多 视频

技术专区