Leetcode: Path Sum II 理解分析
2014-05-02 15:28
423 查看
题目大意:给定一个二叉树和一个sum,找到树中所有从根到叶子节点的所有和等于sum的路径。
理解:
1)本题是Path Sum(http://blog.csdn.net/blog_szhao/article/details/23385869)的扩展。二叉树中每个节点的值均为整型,所以不到叶子节点均无法判断该条路径的和是否等于sum;
2)遇到二叉树的题,一般可以考虑用递归进行解决。本人采用先根遍历的方法。
实现:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
private ArrayList<Integer> arr = new ArrayList<Integer>();
private int total = 0;
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
if(root == null) return res;
total += root.val;
arr.add(root.val);
if(root.left == null && root.right == null) {
if(total == sum) {
ArrayList<Integer> tmp = new ArrayList<Integer>();
for(int i = 0; i < arr.size(); i ++) tmp.add(arr.get(i));
res.add(tmp);
}
}
if(root.left != null) {
pathSum(root.left, sum);
}
if(root.right != null) {
pathSum(root.right, sum);
}
arr.remove(arr.size() - 1); // 递归状态恢复
total -= root.val;
return res;
}
}
理解:
1)本题是Path Sum(http://blog.csdn.net/blog_szhao/article/details/23385869)的扩展。二叉树中每个节点的值均为整型,所以不到叶子节点均无法判断该条路径的和是否等于sum;
2)遇到二叉树的题,一般可以考虑用递归进行解决。本人采用先根遍历的方法。
实现:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
private ArrayList<Integer> arr = new ArrayList<Integer>();
private int total = 0;
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
if(root == null) return res;
total += root.val;
arr.add(root.val);
if(root.left == null && root.right == null) {
if(total == sum) {
ArrayList<Integer> tmp = new ArrayList<Integer>();
for(int i = 0; i < arr.size(); i ++) tmp.add(arr.get(i));
res.add(tmp);
}
}
if(root.left != null) {
pathSum(root.left, sum);
}
if(root.right != null) {
pathSum(root.right, sum);
}
arr.remove(arr.size() - 1); // 递归状态恢复
total -= root.val;
return res;
}
}
相关文章推荐
- 【LeetCode】113. Path Sum II 基于Java和C++的解法及分析
- Leetcode: Path Sum 理解分析
- leetcode -- Path Sum II --- 重点,未理解
- #leetcode#Path Sum II
- LeetCode 113: Path Sum II 二叉树遍历
- 【Leetcode】Path Sum II
- LeetCode Path Sum II
- 【leetcode c++】113 Path Sum II
- leetcode: Path Sum II
- LeetCode Path Sum II路径和II
- Leetcode: Two Sum 理解分析
- [Leetcode]Path Sum II
- 113. Path Sum II LeetCode
- leetcode:Path Sum II
- [Leetcode] #112#113 Path Sum I & II
- Path Sum II - LeetCode
- LeetCode Path Sum II
- [leetCode]Path Sum&&Path Sum II
- 【LeetCode】path-sum i&ii
- LeetCode力扣之113. Path Sum II