【树】113. 路径总和 II(今晚总结)

题目:

给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

说明: 叶子节点是指没有子节点的节点。

示例:
给定如下二叉树,以及目标和 sum = 22,

5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:

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

 

解答:

方法一:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        
        preOrder(root,new ArrayList<Integer>(),sum);

        return res;
    }

    public void preOrder(TreeNode root, List<Integer> list, int sum){
        if(root == null) return;
        List<Integer> curList = new ArrayList<>(list);
        curList.add(root.val);
        if(root.left == null && root.right == null ){
            int cnt = 0;
            for(int num:curList) cnt +=num;
            if(cnt == sum)  res.add(curList);
        }

        preOrder(root.left,curList,sum);
        preOrder(root.right,curList,sum);
    }
}

方法二:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        //这里使用LinkedList,为了使用removeLast方法
        // 定义一个有序list来存储路径
        LinkedList<Integer> list = new LinkedList<>();
        preOrder(root,list,sum);

        return res;
    }

    public void preOrder(TreeNode root,LinkedList<Integer> list,int sum){
        if(root == null) return;

        // 记录路径
        list.add(root.val);
        if(root.left == null && root.right == null && root.val == sum){
            //使用ArrayList的构造方法为:public ArrayList(Collection<? extends E> c)
            res.add(new ArrayList<Integer>(list));
        }

        preOrder(root.left,list,sum-root.val);
        preOrder(root.right,list,sum-root.val);

        //重点,遍历完后,需要把当前节点remove出去,因为用的是同一个list对象来存所有的路径
        list.removeLast();
    }
}

 

posted @ 2020-09-19 18:13  3KBLACK  阅读(61)  评论(0)    收藏  举报