1. 题目
2. 思路
(1) DFS
- 利用深度优先搜索遍历二叉树,若结点为左叶子结点,则记录该结点的值即可。
3. 代码
public class Test {
public static void main(String[] args) {
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
private int sum;
public int sumOfLeftLeaves(TreeNode root) {
sum = 0;
preorder(root);
return sum;
}
private void preorder(TreeNode root) {
if (root == null) {
return;
}
if (root.left != null && root.left.left == null && root.left.right == null) {
sum += root.left.val;
}
preorder(root.left);
preorder(root.right);
}
}