题目:左叶子之和
计算给定二叉树的所有左叶子之和。
复制代码
示例:
3
/ \
9 20
/ \
15 7
在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
复制代码
思考:
这道题还是想到递归。
如果满足root.left != null && root.left.left == null && root.left.right == null,
说明root节点的左节点是叶子节点,则返回该左叶子节点的val加上root节点的右节点中的左叶子节点的val。
否则,说明root的左节点不是左叶子节点,则返回其左右子节点中的的左叶子节点的val的和。
复制代码
实现:
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left != null && root.left.left == null && root.left.right == null) {
return root.left.val + sumOfLeftLeaves(root.right);
}
return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
}
}
复制代码
转载于:https://juejin.im/post/5caad590f265da25057f2e1e