Skip to content

Latest commit

 

History

History
37 lines (25 loc) · 968 Bytes

0404-sum-of-left-leaves.adoc

File metadata and controls

37 lines (25 loc) · 968 Bytes

404. Sum of Left Leaves

{leetcode}/problems/sum-of-left-leaves/[LeetCode - Sum of Left Leaves^]

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. 必须是叶子节点,这个好判断: node.left == null && node.right == null

  2. 还必须是左节点,这个也容易判断: parent.left == node

对上面的两个条件整理,即可得出: parent.left != null && parent.left.left == null && parent.left.right == null。这就是退出递归的一个条件。

其余就是正常的递归的深度优先遍历了。

link:{sourcedir}/_0404_SumOfLeftLeaves.java[role=include]