思路
求的是左叶子节点的和,所以应该用后序遍历。
1.确定递归参数和返回值
返回值:就是左叶子之和。int类型
参数就是当前节点和左叶子的和。
2.递归终止条件
当前节点是nul时返回0;
3.单层递归的含义
如果当前节点的左孩子不为空并且左孩子的左右孩子都是null,就说明当前节点的左孩子是左叶子。就获取其值。
代码
/**
* 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) {
if(root == null){
return 0;
}
int res = 0;
res =fun(root,res);
return res;
}
public int fun(TreeNode temp,int res){
i