LeetCode - 404. Sum of Left Leaves

链接

404. Sum of Left Leaves

题意

求二叉树所有左结点值之和

思路

递归即可,注意判断条件,累加的值必须是左结点且为叶子结点

代码

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.

posted @ 2017-05-09 23:18  zyoung  阅读(82)  评论(0编辑  收藏  举报