您的位置:首页 > 其它

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息