欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

歡迎來到入門教程網(wǎng)!

Java編程

當(dāng)前位置:主頁 > 軟件編程 > Java編程 >

LeetCode -- Path Sum III分析及實(shí)現(xiàn)方法

來源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:Java編程|點(diǎn)擊: 次

LeetCode -- Path Sum III分析及實(shí)現(xiàn)方法

題目描述:

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.


給定一個(gè)二叉樹,遍歷過程中收集所有可能路徑的和,找出和等于X的路徑樹。

思路:

設(shè)當(dāng)前節(jié)點(diǎn)為root,分別收集左右節(jié)點(diǎn)路徑和的集合,merge到當(dāng)前集合中;

將當(dāng)前節(jié)點(diǎn)添加到數(shù)組中,構(gòu)成新的可能路徑。

實(shí)現(xiàn)代碼:

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

如有疑問請(qǐng)留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

上一篇:Java編程GUI中的事件綁定代碼示例

欄    目:Java編程

下一篇:Java編程之繼承問題代碼示例

本文標(biāo)題:LeetCode -- Path Sum III分析及實(shí)現(xiàn)方法

本文地址:http://mengdiqiu.com.cn/a1/Javabiancheng/8447.html

您可能感興趣的文章

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請(qǐng)與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有