題目
給定一顆二叉樹,返回它所有左葉子節(jié)點(diǎn)之和
舉例
3
/ \
9 20
/ \
15 7
return 24
遞歸方法
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
if not root.left and not root.right: #當(dāng)前節(jié)點(diǎn)不存在左右子樹
return 0
if not root.left and root.right: #當(dāng)前節(jié)點(diǎn)只有右子樹
return self.sumOfLeftLeaves(root.right)
if root.left and not root.right: #當(dāng)前節(jié)點(diǎn)只有左子樹
if not root.left.left and not root.left.right: #當(dāng)前節(jié)點(diǎn)的左節(jié)點(diǎn)不存在左右子樹
return root.left.val
else:
return self.sumOfLeftLeaves(root.left)
sum = 0
if root.left and root.right: #當(dāng)前節(jié)點(diǎn)既有左子樹又有右子樹
if not root.left.left and not root.left.right: #當(dāng)前節(jié)點(diǎn)的左子樹沒有左右節(jié)點(diǎn)
sum += root.left.val
else:
sum += self.sumOfLeftLeaves(root.left)
sum += self.sumOfLeftLeaves(root.right)
return sum
簡(jiǎn)化遞歸寫法(參考他人)
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
sum = 0
if root.left and not root.left.left and not root.left.right:
sum += root.left.val
sum += self.sumOfLeftLeaves(root.left)
sum += self.sumOfLeftLeaves(root.right)
return sum