题解 | #NC248 左叶子之和#

左叶子之和

http://www.nowcoder.com/practice/405a9033800b403ba8b7b905bab0463d

public class Solution {
    int sum = 0;
    public int sumOfLeftLeaves (TreeNode root) {
        // write code here
        dfs(root, false);
        return sum;
    }
    void dfs(TreeNode root, Boolean isLeft){
        if(root != null){
            dfs(root.left, true);
            dfs(root.right, false);
            if(root.left == null && root.right == null && isLeft){
                sum += root.val;
            }
        }
    }
}

深度优先遍历,root.left == null && root.right == null判断叶子结点、isLeft标记左。

全部评论

相关推荐

点赞 评论 收藏
分享
05-23 19:02
吉林大学 Java
点赞 评论 收藏
分享
评论
3
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务