链接
题意
求二叉树所有左结点值之和
思路
递归即可,注意判断条件,累加的值必须是左结点且为叶子结点
代码
Java :
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
int sum = 0;
if (root.left != null && root.left.left == null && root.left.right == null) sum += root.left.val;
sum += (sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right));
return sum;
}
}
思考
需要学会list向数组的转换
效率
Your runtime beats 85.75 % of java submissions.