题解:
深度优先搜索(DFS):深度优先搜索是一种通过递归来实现的算法,它可以用来遍历树的所有节点。在遍历过程中,当你发现一个左叶子节点(即该节点是其父节点的左子节点,并且它自己没有子节点)时,就将其值加到总和中。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
def dfs(node):
if not node:
return 0
sum_left = 0
if node.left:
#检查当前节点的左子节点是否是左子节点
if not node.left.left and not node.left.right:
sum_left += node.left.val
else:
sum_left += dfs(node.left)
if node.right:
# 对右子节点递归调用dfs函数(但不检查是否为左叶子,因为我们只对左叶子节点感兴趣)
sum_left += dfs(node.right)
return sum_left
return dfs(root)
广度优先搜索(BFS):广度优先搜索通常使用队列来实现,它按层级遍历树的节点。在遍历过程中,同样检查是否遇到了左叶子节点,并累加其值
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from collections import deque
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
sum_left = 0
queue = deque([root])
while queue:
node = queue.popleft()
if node.left:
if not node.left.left and not node.left.right:
sum_left += node.left.val
else:
queue.append(node.left)
if node.right:
queue.append(node.right)
return sum_left