LeetCode筆記:112. Path Sum

問題:

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,


image.png

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

大意:

給出一個二叉樹和一個值,判斷樹是否有從根節(jié)點到葉子節(jié)點的路徑讓每個節(jié)點的值加起來等于給出的值。
例子:
給出下面的二叉樹以及 sum = 22,


image.png

返回true,因為存在根節(jié)點到葉子節(jié)點的路徑 5->4->11->2 加起來的和為22。

思路:

這個因為只需要判斷有沒有路徑滿足,也就是說只需要找到一條即可,那么采用深度優(yōu)先遍歷比較好,用遞歸來實現(xiàn)。

每次判斷當前路徑的累加和是否等于目標值了,如果等于,因為題目要求從根節(jié)點到葉子節(jié)點,所以還要判斷是否已經(jīng)到葉子節(jié)點了,這個對有無左右子節(jié)點判斷就可以了。

如果還不等于,那么就繼續(xù)判斷走左子節(jié)點或者走右子節(jié)點有沒有等于。

要注意的是題目并沒說節(jié)點值都是正數(shù),我之前對當前的累加和是否已經(jīng)大于了目標值來希望減少一些多余的運算,屬于自作聰明了,對于負數(shù)目標值來說,就完全錯誤了。

代碼(Java):

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        return canSum(root, sum, 0);
    }
    
    public boolean canSum(TreeNode root, int sum, int nowSum) {
        if (root == null) return false;
        
        nowSum = nowSum + root.val;
        System.out.println(nowSum);
        if (nowSum == sum && root.left == null && root.right == null) return true;
        else return canSum(root.left, sum, nowSum) || canSum(root.right, sum, nowSum);
    }
}

合集:https://github.com/Cloudox/LeetCode-Record


查看作者首頁

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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