[LeetCode 404] Sum of Left Leaves

據(jù)說是Facebook的新題,然而被LeetCode標(biāo)為easy。
鏈接:Sum of Left Leaves
題目就是讓找一棵樹左葉子的總和。

想一想,不到一分鐘就有了思路,果然是easy題……

第一版本:

需要判斷當(dāng)前走到的節(jié)點是不是為左葉子。就這一個問題。
這還不好辦,來個flag標(biāo)記一下,于是有了第一個AC的版本

public class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        return helper(root, false);
    }
    
    private int helper(TreeNode node, boolean isLeft) {
        if (node == null) {
            return 0;
        }
        if (node.left == null && node.right == null && isLeft) {
            return node.val;
        }
        return helper(node.left, true) + helper(node.right, false);
    }
}

結(jié)果還不錯,但是想了想,能不能把傳的boolean類型去掉。
于是有了第二個AC的版本。

第二版本:
public class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int sum = 0;
        if (root.left != null && root.left.left == null && root.left.right == null) {
            sum += root.left.val;
        } else {
            sum += sumOfLeftLeaves(root.left);
        }
        sum += sumOfLeftLeaves(root.right);
        return sum;
    }
}

兩個版本都是用的遞歸,根據(jù)LeetCode的runtime分析,第一個版本要稍微快一點。

最后編輯于
?著作權(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)容