404. Sum of Left Leaves
Find the sum of all left leaves in a given binary tree.
Solution1 :Recursive递归,注意:left leaves是左子叶,终端节点才是叶节点。所以只有9和15计算在内
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) {
return 0;
}
int ans = 0;
if (root.left != null) {
if (root.left.left == null && root.left.right == null)
ans += root.left.val;
else
ans += sumOfLeftLeaves(root.left);
}
ans += sumOfLeftLeaves(root.right);
return ans;
}
}
Solution2:
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null || root.left == null && root.right == null) {
return 0;
}
int ans = 0;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
TreeNode tr = q.poll();
if (tr.left != null && tr.left.left == null && tr.left.right == null)
ans += tr.left.val;
if (tr.left != null)
q.offer(tr.left);
if (tr.right != null)
q.offer(tr.right);
}
return ans;
}
}
浙公网安备 33010602011771号