随意随想

知其然,知其所以然

0%

LeetCode 404. 左叶子之和

给定二叉树的根节点 root,返回所有左叶子之和。

示例 1:

输入: root = [3,9,20,null,null,15,7]
输出: 24
解释: 在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24

示例2:
输入: root = [1]
输出: 0

提示:
节点数在[1, 1000]范围内
-1000 <= Node.val <= 1000

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 根节点不是叶子节点
*/
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 0;//这步要主要,当前节点没有孩子节点,所以当前节点是叶子节点,应该返回0
}
int leftint = sumOfLeftLeaves(root.left);
if (root.left != null && root.left.left == null && root.left.right == null) {//判断当节点的左节点是否是叶子节点
leftint = leftint + root.left.val;
}
int rightint = sumOfLeftLeaves(root.right);
return leftint + rightint;
}