404. 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.

链接:https://leetcode.com/problems/sum-of-left-leaves/#/description

3/22/2017

performance并没有特别好,还要注意要求,题目是只求左叶结点,不应该算上右叶结点

 1 public class Solution {
 2     public int sumOfLeftLeaves(TreeNode root) {
 3         if (root == null) return 0;
 4         if (root.left == null && root.right == null) return 0;
 5         return sumOfLeftLeaves(root.left, root) + sumOfLeftLeaves(root.right, root);
 6     }
 7     private int sumOfLeftLeaves(TreeNode root, TreeNode parent) {
 8         if (root == null) return 0;
 9         if (root.left == null && root.right == null) {
10             if (parent.left == root) return root.val;
11             else return 0;
12         }
13         return sumOfLeftLeaves(root.left, root) + sumOfLeftLeaves(root.right, root);
14     }
15 }
原文地址:https://www.cnblogs.com/panini/p/6608786.html