LeetCode之404. Sum of Left Leaves

-------------------------------------------------------------------

分两种情况:

1.当前节点拥有左孩子并且左孩子是叶子节点:左孩子值+右孩子子树遍历统计
2.不符合上面那种情况的从当前节点劈开为两颗子树分别统计相加即可

AC代码:

/**
 * 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;
        else if(root.left!=null && root.left.left==null && root.left.right==null) return root.left.val+sumOfLeftLeaves(root.right);
        else return sumOfLeftLeaves(root.left)+sumOfLeftLeaves(root.right);
    }
}

题目来源: https://leetcode.com/problems/sum-of-left-leaves/

原文地址:https://www.cnblogs.com/cc11001100/p/5997893.html