1. 程式人生 > >leetcode_404 左葉子之和

leetcode_404 左葉子之和

題目描述

計算給定二叉樹的所有左葉子之和。
示例:


    3
   / \
  9  20
    /  \
   15   7

在這個二叉樹中,有兩個左葉子,分別是 9 和 15,所以返回 24

題解

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