Path Sum II(LeetCode)

题目:

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值