题目

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

Example:

  1. 3
  2. / \
  3. 9 20
  4. / \
  5. 15 7
  6. There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

题意

求树中所有左叶结点的值之和。

思路

递归遍历判断是不是左叶结点即可。


代码实现

Java

  1. class Solution {
  2. public int sumOfLeftLeaves(TreeNode root) {
  3. return dfs(root, false);
  4. }
  5. private int dfs(TreeNode p, boolean left) {
  6. if (p == null) {
  7. return 0;
  8. }
  9. if (p.left == null && p.right == null) {
  10. return left ? p.val : 0;
  11. }
  12. return dfs(p.left, true) + dfs(p.right, false);
  13. }
  14. }