leetcode-左叶子之和

404. 左叶子之和

题解:

深度优先搜索(DFS):深度优先搜索是一种通过递归来实现的算法,它可以用来遍历树的所有节点。在遍历过程中,当你发现一个左叶子节点(即该节点是其父节点的左子节点,并且它自己没有子节点)时,就将其值加到总和中。

python 复制代码
# 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):广度优先搜索通常使用队列来实现,它按层级遍历树的节点。在遍历过程中,同样检查是否遇到了左叶子节点,并累加其值

python 复制代码
# 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
相关推荐
艾莉丝努力练剑5 小时前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
珊瑚里的鱼10 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
凌肖战14 小时前
力扣网编程135题:分发糖果(贪心算法)
算法·leetcode
Norvyn_716 小时前
LeetCode|Day11|557. 反转字符串中的单词 III|Python刷题笔记
笔记·python·leetcode
chao_78916 小时前
动态规划题解_零钱兑换【LeetCode】
python·算法·leetcode·动态规划
吃着火锅x唱着歌16 小时前
LeetCode 424.替换后的最长重复字符
linux·算法·leetcode
Maybyy16 小时前
力扣454.四数相加Ⅱ
java·算法·leetcode
逐闲21 小时前
LeetCode热题100【第一天】
算法·leetcode
爱吃涮毛肚的肥肥(暂时吃不了版)21 小时前
剑指offer——模拟:顺时针打印矩阵
算法·leetcode·矩阵
chao_78921 小时前
动态规划题解——乘积最大子数组【LeetCode】
python·算法·leetcode·动态规划