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

所属分类: 软件编程 / Java编程 阅读数: 147
收藏 0 赞 0 分享

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); 
 } 
} 

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

更多精彩内容其他人还在看

常用数据库的驱动程序及JDBC URL分享

这篇文章主要介绍了常用数据库的驱动程序及 JDBC URL,需要的朋友可以看下
收藏 0 赞 0 分享

jackson使用@JsonSerialize格式化BigDecimal解决.00不显示问题

这篇文章主要介绍了jackson使用@JsonSerialize格式化BigDecimal解决.00不显示问题,本文直接给出实现代码,需要的朋友可以参考下
收藏 0 赞 0 分享

Java编程实现中英混合字符串数组按首字母排序的方法

这篇文章主要介绍了Java编程实现中英混合字符串数组按首字母排序的方法,涉及Java字符串操作及拼音转换的相关使用技巧,具有一定参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

详解JAVA类加载机制(推荐)

这篇文章主要介绍了JAVA类加载机制的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

常用Java排序算法详解

本文主要介绍了java的七种常见排序算法的实现,对选择排序、插入排序、冒泡排序、归并排序、快速排序、希尔排序、最小堆排序进行原理分析与实例介绍,具有很好的参考价值。下面就跟着小编一起来看下吧
收藏 0 赞 0 分享

浅谈java中的对象、类、与方法的重载

本文主要对java中的对象、类、与方法的重载进行简要概述,具有一定的参考价值,需要的朋友一起来看下吧
收藏 0 赞 0 分享

详解Http请求中Content-Type讲解以及在Spring MVC中的应用

这篇文章主要介绍了Http请求中Content-Type讲解以及在Spring MVC中的应用的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

JSP request.setAttribute()详解及实例

这篇文章主要介绍了 javascript request.setAttribute()详解及实例的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

Java 回调函数详解及使用

这篇文章主要介绍了Java 回调函数详解及使用,附有简单实例,需要的朋友可以参考下
收藏 0 赞 0 分享

java中Cookie被禁用后Session追踪问题

这篇文章主要介绍了Java中Cookie被禁用后Session追踪问题,非常不错,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多