给定一颗二叉树,返回它所有左叶子节点之和
Example:
3
/ \
9 20
/ \
15 7There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
1:递归方法
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
if not root.left and not root.right: #当前节点不存在左右子树
return 0
if not root.left and root.right: #当前节点只有右子树
return self.sumOfLeftLeaves(root.right)
if root.left and not root.right: #当前节点只有左子树
if not root.left.left and not root.left.right: #当前节点的左节点不存在左右子树
return root.left.val
else:
return self.sumOfLeftLeaves(root.left)
sum = 0
if root.left and root.right: #当前节点既有左子树又有右子树
if not root.left.left and not root.left.right: #当前节点的左子树没有左右节点
sum += root.left.val
else:
sum += self.sumOfLeftLeaves(root.left)
sum += self.sumOfLeftLeaves(root.right)
return sum
简化写法(参考他人)
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
2:迭代方法
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
sum = 0
node = [root] #存放节点
while node:
cur = node.pop(0) #当前节点
if not cur.left and not cur.right: #当前节点无左右子树
continue
elif cur.left and not cur.right: #当前节点有左子树无右子树
if not cur.left.left and not cur.left.right: #当前节点的左子树无左右子树,满足左叶子节点条件
sum += cur.left.val
else:
node.append(cur.left)
elif not cur.left and cur.right: #当前节点无左子树有右子树
node.append(cur.right)
else: #当前节点有左右子树
if not cur.left.left and not cur.left.right: #当前节点的左子树无左右子树,满足左叶子节点条件
sum += cur.left.val
else:
node.append(cur.left)
node.append(cur.right)
return sum
简化写法(参考他人)
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
sum = 0
node = [root] #存放节点
while node:
cur = node.pop(0) #当前节点
if cur.left:
if not cur.left.left and not cur.left.right:
sum += cur.left.val
else:
node.append(cur.left)
if cur.right:
node.append(cur.right)
return sum
算法题来自:https://leetcode-cn.com/problems/sum-of-left-leaves/description/