欢迎来到入门教程网!

Java编程

当前位置:主页 > 软件编程 > Java编程 >

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

来源:本站原创|时间:2020-01-10|栏目:Java编程|点击:

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编程GUI中的事件绑定代码示例

栏    目:Java编程

下一篇:Java编程之继承问题代码示例

本文标题:LeetCode -- Path Sum III分析及实现方法

本文地址:https://www.xiuzhanwang.com/a1/Javabiancheng/8447.html

您可能感兴趣的文章

网页制作CMS教程网络编程软件编程脚本语言数据库服务器

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:835971066 | 邮箱:835971066#qq.com(#换成@)

Copyright © 2002-2020 脚本教程网 版权所有