Leetcode刷題java之437. 路徑總和 III

執行結果:

通過

顯示詳情

執行用時 :16 ms, 在所有 Java 提交中擊敗了70.04% 的用戶

內存消耗 :41.3 MB, 在所有 Java 提交中擊敗了12.40%的用戶

題目:

給定一個二叉樹,它的每個結點都存放着一個整數值。

找出路徑和等於給定數值的路徑總數。

路徑不需要從根節點開始,也不需要在葉子節點結束,但是路徑方向必須是向下的(只能從父節點到子節點)。

二叉樹不超過1000個節點,且節點數值範圍是 [-1000000,1000000] 的整數。

示例:

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

      10
     /  \
    5   -3
   / \    \
  3   2   11
 / \   \
3  -2   1

返回 3。和等於 8 的路徑有:

1.  5 -> 3
2.  5 -> 2 -> 1
3.  -3 -> 11

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/path-sum-iii
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

思路:

雙遞歸,把所有節點當作頭,然後對於每一個頭在進行遞歸。

代碼:

/**
 * 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) {
        if(root==null)
        {
            return 0;
        }
        return help(root,sum)+pathSum(root.left,sum)+pathSum(root.right,sum);
    }
    public int help(TreeNode root,int sum)
    {
        if(root==null)
        {
            return 0;
        }
        int count=0;
        if(root.val==sum)
        {
            count++;
        }
        count+=help(root.left,sum-root.val);
        count+=help(root.right,sum-root.val);
        return count;
    }
}

 

發佈了476 篇原創文章 · 獲贊 485 · 訪問量 23萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章