404. Sum of Left Leaves

来源:互联网 发布:互联网灰色产业链知乎 编辑:程序博客网 时间:2024/05/01 00:47

Find the sum of all left leaves in a given binary tree.

Example:

    3   / \  9  20    /  \   15   7There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

自己的方法稍微有一些naive,思路是一直找左节点,找到之后sum累加,但是root.left == null && root.right == null的判断方法会误判右子节点,不如用root.left.left == null && root.left.right == null,先记录自己的代码,代码如下:

/** * 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 || (root.left == null && root.right == null)) {            return 0;        }        int[] sum = new int[1];        findleftleave(root, sum, 0);        return sum[0];    }    public int findleftleave(TreeNode root, int[] sum, int val) {        if (root.left == null && root.right == null) {            sum[0] = sum[0] + root.val;        }        if (root.left != null) {            findleftleave(root.left, sum, root.val) ;        }        if (root.right != null && (root.right.left != null || root.right.right != null)) {            findleftleave(root.right, sum, root.val);        }        return sum[0];    }}
比较好的方法如下:

public class Solution {    public int sumOfLeftLeaves(TreeNode root) {    if(root == null) return 0;    int ans = 0;    if(root.left != null) {        if(root.left.left == null && root.left.right == null) ans += root.left.val;        else ans += sumOfLeftLeaves(root.left);    }    ans += sumOfLeftLeaves(root.right);        return ans;    }}

0 0