LeetCode -- Path Sum III
来源:互联网 发布:做淘宝需要哪些软件 编辑:程序博客网 时间:2024/05/01 02:17
题目描述:
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到当前集合中;
将当前节点添加到数组中,构成新的可能路径。
实现代码:
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); }}
1 0
- LeetCode-Path Sum III
- path sum iii-leetcode
- Path Sum III ---LeetCode
- Leetcode | Path Sum III
- Leetcode Path Sum III
- LEETCODE--Path Sum III
- LeetCode -- Path Sum III
- LeetCode : Path Sum III
- LeetCode 437. Path Sum III
- LeetCode 437. Path Sum III
- LeetCode 437. Path Sum III
- leetcode 437. Path Sum III
- [LeetCode]437. Path Sum III
- LeetCode 437 Path Sum III
- 【LeetCode】 437. Path Sum III
- [leetcode]437. Path Sum III
- LeetCode 437. Path Sum III
- [leetcode]437. Path Sum III
- 2、servlet容器(Tomcat)
- 面试题39:二叉树的深度
- 深入理解RunLoop[转载]
- 程序运行时内存区域使用与管理
- java之异常的处理!!!
- LeetCode -- Path Sum III
- 经典排序算法 - 选择排序Selection sort
- Oracle 存储过程中自定义异常
- 面试题39-题目2:平衡二叉树
- 谨慎能捕千秋蝉(三)——界面操作劫持与HTML5安全
- android--Activity设置全屏或无标题
- Java集合系列(12)--总目录
- java反射详解
- Autodesk Softimage xsi 2013中文破解版安装教程