题目链接
https://leetcode-cn.com/problems/sum-of-left-leaves/
描述
计算给定二叉树的所有左叶子之和。
示例
3
/ \
9 20
/ \
15 7
在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
代码
其实不定义全局变量也是可以的,只是我觉得这样更方便一些
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int ans = 0;
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) {
return 0;
}
count(root, false);
return ans;
}
private void count(TreeNode root, Boolean isLeft) {
if (root.left == null && root.right == null && isLeft) {
ans += root.val;
}
if (root.left != null) {
count(root.left, true);
}
if (root.right != null) {
count(root.right, false);
}
}
}