链接:https://leetcode-cn.com/problems/sum-of-left-leaves/
计算给定二叉树的所有左叶子之和。
示例:
3
/ \
9 20
/ \
15 7
在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
题目中要求的是左叶子,而不是左节点。所以我们可以对整棵树进行遍历,当遍历到某个节点的时候,判断它是否是左叶子。左叶子节点的判断是当前节点是某个节点的左子节点,且是叶子节点,这时我们可以对左叶子进行累加,最后得到要求的全部左叶子之和。而遍历的方法可以通过深度优先遍历 (DFS) 和广度优先遍历 (BFS),接下来我们看下代码的实现。
时间复杂度:O(n)
空间复杂度:O(n)
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
if not root:
return 0
ans = 0
if root.left and not root.left.left and not root.left.right:
ans += root.left.val
ans += self.sumOfLeftLeaves(root.left)
ans += self.sumOfLeftLeaves(root.right)
return ans
注意:queue.pop() 和 node=queue.pop(0) 的区别,queue.pop() 的时间复杂度是 O(1),queue.pop(0) 的时间复杂度是 O(n)。
时间复杂度:O(n)
空间复杂度:O(n)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
if not root:
return 0
queue=[root]
ans=0
while queue:
node=queue.pop()
if node.left and not node.left.left and not node.left.right:
ans+=node.left.val
if node.right:
queue.append(node.right)
if node.left:
queue.append(node.left)
return ans
如果大家觉得文章还不错,可以关注我噢,我会不定期分享的。