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

404. 左葉子之和

題目

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

示例:

    3
   / \
  9  20
    /  \
   15   7

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

思路

遞迴實現。

程式碼

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        int count = 0;
        if(root==null){      // 根節點為空直接返回count
            return count;
        }
        if(root.left != null && root.left.left == null && root.left.right == null){    // 判斷是否為左葉子結點
            count += root.left.val;
        }
        count += sumOfLeftLeaves(root.left);   //遞迴
        count += sumOfLeftLeaves(root.right);
        return count;
    }
}