【leetcode】404 左叶子之和
https://leetcode.cn/problems/sum-of-left-leaves/description/
【分析】
该题要求左叶子之和。
如果我们对当前节点进行叶子节点的判断,那么我们是不知道当前节点是左叶子还是右叶子的。
所以我们应该在叶子结点的上层(父节点)进行判断。
【代码】
class Solution: def sumOfLeftLeaves(self, root) -> int: if not root or (root.left is None and root.right is None): return 0 cur = 0 if root.left and root.left.left is None and root.left.right is None: cur = root.left.val return cur + self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)
【更新代码】
class Solution:
def sumOfLeftLeaves(self, root) -> int:
if root is None:
return 0
if root.left is None and root.right is None:
return 0
if root.left and root.left.left is None and root.left.right is None:
return self.sumOfLeftLeaves(root.left) + root.left.val + self.sumOfLeftLeaves(root.right)
return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)