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

 

 


题目标签:Tree
  这道题目给了我们一个二叉树,让我们找到所有左子叶之和。这里需要另外一个function - sumLeftLeaves 还要一个int res在两个functions外。对于sumLeftLeaves, 不需要返回,依次遍历每一个点,直到这个点是一个leaf node,就停止递归了。对于每一个点,有四种情况:
  1。这个点的两个children 都不是null, 这里需要检测left 是不是一个 leaf node, 如果是的话,加入它的值,继续递归left 和 right;
  2。这个点的left 是null, right 不是null, 那么递归right;
  3。这个点的left 不是null, right是null,需要检测left 是不是 left node, 是就加上它的值,继续递归left。
  4。这个点的两个children 都是null, 什么都不用写,不用递归,它自然停止。
 
 

Java Solution:

Runtime beats 77.28% 

完成日期:07/05/2017

关键词:Tree

关键点:利用递归function 但是不需要返回,只遍历;

 

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution 
11 {
12     int res = 0;
13     public int sumOfLeftLeaves(TreeNode root) 
14     {
15         if(root == null)
16             return res;
17         
18         sumLeftLeaves(root);
19         
20         return res;
21     }
22     
23     public void sumLeftLeaves(TreeNode root)
24     {
25         if(root.left != null && root.right != null)
26         {
27             if(root.left.left == null && root.left.right == null)
28                 res += root.left.val;
29             
30             sumLeftLeaves(root.left);
31             sumLeftLeaves(root.right);
32         }
33         else if(root.left == null && root.right != null)
34         {
35             sumLeftLeaves(root.right);
36         }
37         else if(root.right == null && root.left != null)
38         {
39             if(root.left.left == null && root.left.right == null)
40                 res += root.left.val;
41             
42             sumLeftLeaves(root.left);
43         }
44     }
45 }

参考资料:N/A

 

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

posted @ 2017-07-06 23:51  Jimmy_Cheng  阅读(265)  评论(0编辑  收藏  举报