国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Java > 正文

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

2020-01-31 16:50:08
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

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è)二叉樹(shù),遍歷過(guò)程中收集所有可能路徑的和,找出和等于X的路徑樹(shù)。

思路:

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

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

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 龙山县| 秦安县| 麦盖提县| 株洲市| 安龙县| 温宿县| 宣武区| 长治市| 宝丰县| 阳新县| 洪泽县| 齐河县| 伊川县| 土默特右旗| 中阳县| 宿迁市| 搜索| 镇平县| 金湖县| 贡嘎县| 周宁县| 宁强县| 怀远县| 那坡县| 昌平区| 平顺县| 鄂伦春自治旗| 博白县| 鄯善县| 赞皇县| 东城区| 苍梧县| 海口市| 依兰县| 嘉荫县| 沈丘县| 来凤县| 丽江市| 平泉县| 额尔古纳市| 汤原县|