404. 左叶子之和
原题
java
/**
* 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 {
int sum = 0;
public int sumOfLeftLeaves(TreeNode root) {
//第二个参数代表当前结点是左节点(1),还是右节点(0),一开始传0,让头结点不参与运算
dfs(root,0);
return sum;
}
public void dfs(TreeNode node,int i){
if(node==null){
return;
}
//为叶子结点
if(node.left==null&&node.right==null){
//为左叶子节点
if(i==1){
sum += node.val;
}
}
//左子树递归
dfs(node.left,1);
//右子树递归
dfs(node.right,0);
}
}