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題解法的框架上做一些改變。
增加一個(gè)list記錄每次遍歷的路徑,這個(gè)list在回溯到上一個(gè)節(jié)點(diǎn)的時(shí)候需要把當(dāng)前點(diǎn)從list中刪除。
找到了滿足條件的路徑后,需要把這個(gè)路徑的list加到結(jié)果集中,此時(shí)需要加一個(gè)new ArrayList,如果直接加傳參的list,由于引用的性質(zhì)會(huì)有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)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容