leetcode404. 左叶子之和

版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/love905661433/article/details/85008846

题目

计算给定二叉树的所有左叶子之和。

示例:

    3
   / \
  9  20
    /  \
   15   7

在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24

解题

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        return sumOfLeftLeaves(root,false);
    }

    private int sumOfLeftLeaves(TreeNode root, boolean isLeft) {
        if (root == null) {
            return 0;
        }
        // 是否为左叶子节点
        if (isLeft && root.left == null && root.right == null) {
            return root.val;
        } else {
            return sumOfLeftLeaves(root.left, true) + sumOfLeftLeaves(root.right, false);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/love905661433/article/details/85008846