Path Sum II(LeetCode)

来源:互联网 发布:打印软件下载 编辑:程序博客网 时间:2024/06/06 09:50

题目:

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and sum = 22,
              5             / \            4   8           /   / \          11  13  4         /  \    / \        7    2  5   1

return

[   [5,4,11,2],   [5,8,4,5]]

题目分析:

这一题遇上一题类似,都是求根到叶子的路径和是否等于sum。不过,这一题要求将所有符合条件的路径返回。


思路:

  1. 深度优先遍历二叉树
    • lastPath记录到父节点的路径,thisPath记录到本节点的路径
    • 当是符合条件的叶子节点时,将thisPath放入result中。
    • 否则,继续递归搜寻左孩子、右孩子



注意点:

  1. 对于引用类型,形参传递了指针的地址。当在方法中改变这一引用类型的时候,其值是被实际改变了。
    • 所以getPath方法中,thisPath需要新建一个实例,才能再放入最后的result中或者传递给下一个递归地getPath
  2. 注意对于接口的使用
    • 接口是不能使用所实现类的方法的。例如:List<Integer> thisPath = new ArrayList<Integer>(),thisPath只能用List接口中的方法addAll,而不能用ArrayList类中的方法clone。(不过,这一点不是十分的确定,需要再学习确认)
    • 注意List接口中的addAll方法的使用,不用手工遍历复制了。(addAll是shallow copy)



代码:

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    static List<List<Integer>> result;    public List<List<Integer>> pathSum(TreeNode root, int sum) {        result = new ArrayList<List<Integer>>();        List<Integer> thisPath = new ArrayList<Integer>();        getPath(root, sum, thisPath);        return result;    }        static void getPath(TreeNode node, int sum, List<Integer> lastPath){        if (node == null){            return;        }        List<Integer> thisPath;        if(node.left == null && node.right == null){            if(node.val == sum){                thisPath = new ArrayList<Integer>();                thisPath.addAll(lastPath);                thisPath.add(node.val);                result.add(thisPath);            }            return;        }        thisPath = new ArrayList<Integer>();        thisPath.addAll(lastPath);        thisPath.add(node.val);        getPath(node.left, sum - node.val, thisPath);        getPath(node.right, sum - node.val, thisPath);    }}





0 0
原创粉丝点击