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

所属分类: 软件编程 / Java编程 阅读数: 65
收藏 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); 
 } 
} 

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

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

SWT(JFace) FTP客户端实现

SWT(JFace)小制作:FTP客户端实现
收藏 0 赞 0 分享

java多线程应用实现方法

以前没有写笔记的习惯,现在慢慢的发现及时总结是多么的重要了,呵呵。虽然才大二,但是也快要毕业了,要加油
收藏 0 赞 0 分享

java反射应用详细介绍

本篇文章依旧采用小例子来说明java反射应用,因为我始终觉的,案例驱动是最好的,需要的朋友可以参考下
收藏 0 赞 0 分享

java 逐行读取txt文本如何解决中文乱码

在使用java读取txt文本中如含有中文,可能会出现乱码,很多初学者束手无策,本文将提供详细的解决方法
收藏 0 赞 0 分享

Java中Runnable和Thread的区别分析

在java中可有两种方式实现多线程,一种是继承Thread类,一种是实现Runnable接口,下面就拉分别介绍一下这两种方法的优缺点
收藏 0 赞 0 分享

深入jetty的使用详解

本篇文章是对jetty的使用进行了详细的分析解释。需要的朋友参考下
收藏 0 赞 0 分享

探讨:如何在NDK中呼叫Java的class

本篇文章是对如何在NDK中呼叫Java的class进行了详细的分析介绍,需要的朋友参考下
收藏 0 赞 0 分享

Java equals 方法与hashcode 方法的深入解析

面试时经常会问起字符串比较相关的问题,比如:字符串比较时用的什么方法,内部实现如何?hashcode的作用,以及重写equal方法,为什么要重写hashcode方法?以下就为大家解答,需要的朋友可以参考下
收藏 0 赞 0 分享

Java使用默认浏览器打开指定URL的方法(二种方法)

Java使用默认浏览器打开指定URL。
收藏 0 赞 0 分享

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

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