标签:递归 依次 targe 检测 logs htm log turn 参考
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.
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
LeetCode 404. Sum of Left Leaves (左子叶之和)
标签:递归 依次 targe 检测 logs htm log turn 参考
原文地址:http://www.cnblogs.com/jimmycheng/p/7129128.html