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.
左叶子之和。题意是给一个二叉树,返回所有左孩子的值的和。
这道题有BFS和DFS两种思路。这道题不难,但是无论是BFS还是DFS,记住遍历的时候永远都是看当前节点是否有左孩子,如果有,说明有戏,但是别急着先遍历过去,要先看一下这个左孩子自身是否还有子节点,如果有,其实是不满足题意的。如果当前节点有有孩子,就直接加入queue继续下一轮遍历了,不需要再做额外处理。
BFS
时间O(n)
空间O(n)
Java实现
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 public int sumOfLeftLeaves(TreeNode root) { 18 // corner case 19 if (root == null) { 20 return 0; 21 } 22 // normal case 23 int res = 0; 24 Queue<TreeNode> queue = new LinkedList<>(); 25 queue.offer(root); 26 while (!queue.isEmpty()) { 27 TreeNode cur = queue.poll(); 28 if (cur.left != null) { 29 if (cur.left.left == null && cur.left.right == null) { 30 res += cur.left.val; 31 } else { 32 queue.offer(cur.left); 33 } 34 } 35 if (cur.right != null) { 36 queue.offer(cur.right); 37 } 38 } 39 return res; 40 } 41 }
DFS
时间O(n)
空间O(n)
Java实现
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 public int sumOfLeftLeaves(TreeNode root) { 18 if (root == null) { 19 return 0; 20 } 21 int res = 0; 22 if (root.left != null) { 23 if (root.left.left == null && root.left.right == null) { 24 res += root.left.val; 25 } else { 26 res += sumOfLeftLeaves(root.left); 27 } 28 } 29 res += sumOfLeftLeaves(root.right); 30 return res; 31 } 32 }