1.题目描述
2.思路
递归遍历左子树 ,然后再把左子树的和相加
3.代码实现
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public int sumOfLeftLeaves(TreeNode root) {return dfs(root,false);//它调用 dfs 方法,传入根节点 root 和布尔值 false。根节点没有父节点,所以 isLeft 设置为 false。}private int dfs(TreeNode node,boolean isLeft){if(node==null)//节点为空{return 0;}if(node.right==null&&node.left==null&&isLeft)//如果是叶子节点,而且是左叶子{return node.val;//返回节点的值}return dfs(node.left,true)+dfs(node.right,false);//继续搜索左子树和右子树}}