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

這題我一拿到就感覺應該用DFS保護現場那套來做,但沒寫出來,因為不知道remove在哪操作。

參考了code ganker的代碼調試了一陣子AC了。

public class Solution {
    List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        if (root == null) return res;
        List<Integer> cell = new ArrayList<>();
        cell.add(root.val);
        helper(root, sum - root.val, cell);
        return res;
    }


    private void helper(TreeNode root, int sum, List<Integer> cell) {
        if (root == null) return;

        if (root.left == null && root.right == null && 0 == sum) {
            res.add(new ArrayList<>(cell));
            //相當于else
            return;
        }
        if (root.left != null ) {
            cell.add(root.left.val);
            helper(root.left, sum - root.left.val, cell);
            cell.remove(cell.size() - 1);
        }
        if (root.right != null ) {
            cell.add(root.right.val);
            helper(root.right, sum - root.right.val, cell);
            cell.remove(cell.size() - 1);
        }
    }
}

需要注意的地方:

  1. 這題跟上題不一樣,它先把root加進初始cell表里去,然后才去遞歸找left和right。為什么不能直接把root放進去,我想是因為不好判斷,因為
        if (root.left != null && sum > 0) {
            cell.add(root.left.val);
            helper(root.left, sum - root.left.val);
            cell.remove(cell.size() - 1);
        }

這三行是套路,不能在套路外面add node啊。

  1. 第二是要在root為null的時候和滿足條件之后就return(廢話)。

  2. 第三是res.add(new ArrayList<>(cell));這句話不能用res.add(cell); cell = new ArrayList<>();這兩句來代替,因為這是dfs啊,后面還要保護現場呢,你找到一個結果之后它要在你原先的結果后面remove的,如果new了,后面remove的時候直接就out of bounds -1了。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,769評論 0 33
  • Given a binary tree and a sum, find all root-to-leaf path...
    greatseniorsde閱讀 173評論 0 0
  • Given a binary tree and a sum, find all root-to-leaf path...
    matrxyz閱讀 154評論 0 0
  • Given a binary tree and a sum, find all root-to-leaf path...
    Jeanz閱讀 173評論 0 0
  • 世間最令人感動的情感,也許就是親子之間的牽絆。 來英國讀書的第二個月的某一天早晨,坐巴士去學校圖書館。清晨的陽光慷...
    隱秘角落閱讀 298評論 0 0