My code:
recursion
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) {
return 0;
}
int ret = 0;
if (root.left != null) {
if (root.left.left == null && root.left.right == null) {
ret += root.left.val;
}
else {
ret += sumOfLeftLeaves(root.left);
}
}
if (root.right != null) {
ret += sumOfLeftLeaves(root.right);
}
return ret;
}
}
iteration:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(root);
int ret = 0;
while (!q.isEmpty()) {
TreeNode curr = q.poll();
if (curr.left != null) {
if (curr.left.left == null && curr.left.right == null) {
ret += curr.left.val;
}
else {
q.offer(curr.left);
}
}
if (curr.right != null) {
q.offer(curr.right);
}
}
return ret;
}
}
reference:
https://discuss.leetcode.com/topic/60403/java-iterative-and-recursive-solutions/2
竟然没写出来。哎,早点休息了。
Anyway, Good luck, Richardo! -- 10/11/2016