1. 程式人生 > >[LeetCode] 404. Sum of Left Leaves

[LeetCode] 404. Sum of Left Leaves

題:https://leetcode.com/problems/sum-of-left-leaves/description/

題目

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

Example:

    3
   / \
  9  20
    /  \
   15   7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

題目大意

求所有左葉子的和。其中左葉子的定義為:1.為葉子;2.為某結點的左子樹。

思路

先序遍歷,若一個結點為左子樹為 葉子,那麼累加。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int tsum = 0;
    public void dfs(TreeNode root){
        if(root == null)
return; if(root.left != null && root.left.left == null && root.left.right == null) tsum += root.left.val; dfs(root.left); dfs(root.right); } public int sumOfLeftLeaves(TreeNode root) { dfs(root); return
tsum; } }