LeetCode每日一题:二叉树路径和 2

问题描述

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]
]

问题分析

和上题一样,采用递归就可以了,但是要记得保存中间结果,用DFS搜索最后一行要加上list.remove(list.size() - 1);//不加这句就超时了

代码实现

public ArrayList> pathSum(TreeNode root, int sum) {
        ArrayList> result = new ArrayList<>();
        ArrayList list = new ArrayList<>();
        getPath(root, sum, list, result);
        return result;
    }

    private void getPath(TreeNode root, int sum, ArrayList list, ArrayList> result) {
        if (root == null) return;
        list.add(root.val);
        if (root.val == sum && root.left == null && root.right == null) {
            result.add(new ArrayList(list));
        }
        if (root.left != null) {
            getPath(root.left, sum - root.val, list, result);
        }
        if (root.right != null) {
            getPath(root.right, sum - root.val, list, result);
        }
        list.remove(list.size() - 1);//不加这句就超时了
    }

你可能感兴趣的:(LeetCode每日一题:二叉树路径和 2)