题目:
题解:
需要满足以下两点:
- 必须要是叶子节点
- 必须是左边的叶子节点
dfs 遍历整颗二叉树,遍历左右树时带上遍历方位,当满足以上两点要求时累计节点值。
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) {
return 0;
}
return sumOfLeftLeavesDfs(root, "", 0);
}
private int sumOfLeftLeavesDfs(TreeNode root, String direction, int sum) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null && "L".equals(direction)) {
return sum + root.val;
}
return sumOfLeftLeavesDfs(root.left, "L", sum) + sumOfLeftLeavesDfs(root.right, "R", sum);
}
时间复杂度:O(n)