LeetCode404-左叶子之和

题目链接

英文链接:https://leetcode.com/problems/sum-of-left-leaves/

中文链接:https://leetcode-cn.com/problems/sum-of-left-leaves/

题目详述

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

示例:

1
2
3
4
5
6
7
    3
/ \
9 20
/ \
15 7

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

题目详解

  1. 如果为 null,直接返回 0。
  2. 如果为左叶子,则返回左叶子的值加上递归右子树得到的结果。
  3. 直接返回递归左子树和右子树的结果。
1
2
3
4
5
6
7
8
9
10
11
12
public class LeetCode_00404 {

public int sumOfLeftLeaves(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left != null && root.left.left == null && root.left.right == null) {
return root.left.val + sumOfLeftLeaves(root.right);
}
return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
}
}