久久ER99热精品一区二区-久久精品99国产精品日本-久久精品免费一区二区三区-久久综合九色综合欧美狠狠

博客專欄

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在線教程供學員觀看學習,心動的小伙伴快快行動吧??鄱W堂java技術交流群:487098661。微信號:codingbb

*博客內容為網友個人發布,僅代表博主個人觀點,如有侵權請聯系工作人員刪除。



關鍵詞:

相關推薦

技術專區

關閉