Sum of Left Leaves 07/25

这道题是由大问题变成小问题,遇到二叉树的问题,先想一下,整个题的问题在每个子树上的答案是什么,在这里,把root看做是老大,想要一个答案,就把问题抛给左右儿子,如果左右儿子是最小的子树(他的左右儿子都是叶),那么就能判断找到左叶子的值,然后一层一层返回

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: t
     * @return: the sum of all left leaves
     */
    public int sumOfLeftLeaves(TreeNode root) {
        // Write your code here
        
        if(root == null){
            return 0;
        }
        
        int sum = 0;
        
        if(root.left != null){
            TreeNode left = root.left;
            
            if(left.left == null && left.right == null){
                sum += left.val;
            }else{
                sum += sumOfLeftLeaves(left);
            }
            
        }
        
        if(root.right != null){
            TreeNode node = root.right;
            sum += sumOfLeftLeaves(node);
        }
        
        return sum;
    }
}

Last updated