404. 左叶子之和(递归)
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 {
public int sumOfLeftLeaves(TreeNode root) {
if(root == null){//递归边界
return 0;
}
if(root.left != null && root.left.left == null && root.left.right == null){//找到左叶子
return root.left.val += sumOfLeftLeaves(root.right);//递归右子树
}
return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);//递归下一层
}
}