Leetcode 113. Path Sum II

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

題意:是112題的followup,要求輸出所有符合條件的路徑。

思路:
在112題解法的框架上做一些改變。
增加一個list記錄每次遍歷的路徑,這個list在回溯到上一個節(jié)點(diǎn)的時候需要把當(dāng)前點(diǎn)從list中刪除。
找到了滿足條件的路徑后,需要把這個路徑的list加到結(jié)果集中,此時需要加一個new ArrayList,如果直接加傳參的list,由于引用的性質(zhì)會有bug。

public List<List<Integer>> pathSum(TreeNode root, int sum) {
    List<List<Integer>> res = new ArrayList<>();
    if (root == null) {
        return res;
    }

    dfs(root, sum, new ArrayList<>(), res);
    return res;
}

public void dfs(TreeNode root, int sum, List<Integer> list, List<List<Integer>> res) {
    list.add(root.val);
    if (root.left == null && root.right == null) {
        if (root.val == sum) {
            res.add(new ArrayList<>(list));
        }
        list.remove(list.size() - 1);
        return;
    }

    if (root.left != null) {
        dfs(root.left, sum - root.val, list, res);
    }

    if (root.right != null) {
        dfs(root.right, sum - root.val, list, res);
    }
    list.remove(list.size() - 1);
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容