一、题目描述
二、思路分析
- 分析
这题思路挺简单的,对二叉树的遍历加上判断左叶子条件就行。有两种方法可以解决,分别是深度优先遍历(前序遍历实现)和广度优先遍历(层序遍历实现)。
三、题解
- 深度优先遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private boolean isLeaf(TreeNode node) {
return node.left == null && node.right == null;
}
public int sumOfLeftLeaves(TreeNode root) {
int sum = 0;
if (root == null) {
return 0;
}
if (root.left != null) {
sum += isLeaf(root.left) ? root.left.val : sumOfLeftLeaves(root.left);
}
if (root.right != null && !isLeaf(root.right)) {
sum += sumOfLeftLeaves(root.right);
}
return sum;
}
}
- 广度优先遍历
class Solution {
private boolean isLeaf(TreeNode node) {
return node.left == null && node.right == null;
}
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int sum = 0;
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node.left != null) {
if (isLeaf(node.left)) {
sum += node.left.val;
} else {
queue.offer(node.left);
}
}
if (node.right != null) {
queue.offer(node.right);
}
}
return sum;
}
}