437. Path Sum III

Easy

You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

Example:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

      10
     /  \
    5   -3
   / \    \
  3   2   11
 / \   \
3  -2   1
Return 3. The paths that sum to 8 are:
1.  5 -> 3
2.  5 -> 2 -> 1
3. -3 -> 11

這道題是要找到滿足sum == target的路徑個數,路徑不一定是root to leaf, 但是必須是從上到下的。注意看一開始的錯誤解法。

submit 1 : int基本類型參數傳入的是值,一旦傳入是不會像傳入引用類型的地址值一樣, 在函數運行過程中地址所指向的值會改變的。所以你的res = 0傳到函數里,res的值永遠不會改變,一直是0.


image.png

submit 2 : 邊界條件錯誤, for循環執行的條件是邊界條件為true,跟while一樣。所以這里你表達的意思應該是i >= 0,而不是i== 0, 后者作為邊界條件時for循環根本不會執行。

53D7D469-5DB1-46DA-9151-9D35E1BC5AF2.png
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int pathSum(TreeNode root, int sum) {
        List<Integer> path = new ArrayList<>();
        return helper(root, path, sum); 
    }
    
    private int helper(TreeNode root, List<Integer> path, int sum){
        int res = 0;
        if (root == null){
            return res;
        }
        path.add(root.val);
        int pathSum = 0;
        for (int i = path.size() - 1; i >= 0; i--){
            pathSum += path.get(i);
            if (pathSum == sum){
                res++;
            }
        }
        res += helper(root.left, path, sum);
        res += helper(root.right, path, sum);
        path.remove(path.size() - 1);
        return res;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 題目 You are given a binary tree in which each node contain...
    miltonsun閱讀 359評論 0 0
  • Keywords: double recursion, DFS You are given a binary tr...
    成江閱讀 464評論 0 0
  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,769評論 0 33
  • 想不多寫函數,失敗了,(╯‵□′)╯︵┻━┻ Java,首先要有一個函數記錄某個點開始能找到符合累加和為sum的個...
    hyhchaos閱讀 225評論 0 0
  • 好想為你寫詩,可是不知寫什么; 整日整日的想,可依舊沒有好的句子; 說不出那些感人的話,也不知道怎么表達情感; 不...
    鬼谷擺攤閱讀 274評論 1 1