404. 左叶子之和
题目描述
给定二叉树的根节点 root ,返回所有左叶子之和。
输入: root = [3,9,20,null,null,15,7]
输出: 24
解释: 在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
示例 2:
输入: root = [1]
输出: 0
来源:力扣(LeetCode)
思路
既然是求出当前左叶子的和,意思就是找出我们所有的叶子节点,然后再筛选一下,我们前面做过找出所有的叶子节点,我用的时前序遍历,求出结果,本题就是在求出所有的叶子节点的基础上,稍微改造一下,我们设置一个标志位,标志我们当前遍历的为哪一个节点,是左节点还是右节点,之后就很简单了
代码
/**
* 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 sum = 0;
public int sumOfLeftLeaves(TreeNode root) {
demo(root,0);
return sum;
}
// 确定递归函数的参数和返回值 参数 root ,int
// 每一次递归时,都传递一个参数,告诉当前函数,节点时left 节点还是 right节点
// 0 标识是根节点,第一次传入 1 left 2 right
public void demo(TreeNode root , int type){
// 确定递归终止的条件
if(root == null) return;
// 确定单层逻辑
if(root.left == null && root.right == null && type == 1){
sum += root.val;
return;
}
demo(root.left,1);
demo(root.right,2);
}
}