伙伴云客服论坛»论坛 S区 S软件开发 查看内容

0 评论

0 收藏

分享

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

LeetCode -- Path Sum III分析及实现方法
题目描绘:
  1. You are given a binary tree in which each node contains an integer value.
  2. Find the number of paths that sum to a given value.
  3. 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).
  4. 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到当前集合中;

将当前节点添加到数组中,构成新的可能途径。
实现代码:
  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * public int val;
  5. * public TreeNode left;
  6. * public TreeNode right;
  7. * public TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. private int _sum;
  12. private int _count;
  13. public int PathSum(TreeNode root, int sum)
  14. {
  15. _count = 0;
  16. _sum = sum;
  17. Travel(root, new List<int>());
  18. return _count;
  19. }
  20. private void Travel(TreeNode current, List<int> ret){
  21. if(current == null){
  22.   return ;
  23. }
  24. if(current.val == _sum){
  25.   _count ++;
  26. }
  27. var left = new List<int>();
  28. Travel(current.left, left);
  29. var right = new List<int>();
  30. Travel(current.right, right);
  31. ret.AddRange(left);
  32. ret.AddRange(right);
  33. for(var i = 0;i < ret.Count; i++){
  34.   ret[i] += current.val;
  35.   if(ret[i] == _sum){
  36.   _count ++;
  37.   }
  38. }
  39. ret.Add(current.val);
  40. //Console.WriteLine(ret);
  41. }
  42. }
复制代码
如有疑问请留言或者到本站社区交流讨论,感激阅读,希望能协助到大家,谢谢大家对本站的支持!

回复

举报 使用道具

相关帖子
全部回复
暂无回帖,快来参与回复吧
本版积分规则 高级模式
B Color Image Link Quote Code Smilies

OMG哎呀妈呀
注册会员
主题 17
回复 24
粉丝 0
|网站地图
快速回复 返回顶部 返回列表