2020年9月19日 左叶子之和 sumOfLeftLeaves
/**
* 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) {
}
}
解题思路:
简单题,遍历二叉树,所有left节点的值记入总和。
理解错误,原来求的是叶子节点,不是左节点。
代码实现:
算法没啥特点,甚至有点愚蠢
public int sumOfLeftLeaves(TreeNode root) {
int sum=0;
//如果是叶子节点,返回值
if (root==null)
return 0;
sum+=sumOfLeftLeaves(root.left);
sum+=sumOfLeftLeaves(root.right);
//如果一个节点的左节点是叶子节点,返回该值
if (root.left!=null&&root.left.left==null&&root.left.right==null)
sum+=root.left.val;
return sum;
}