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
相关推荐
ZC跨境爬虫1 小时前
LeetCode 119. 杨辉三角 II(原地更新优化详解 + Java Python 实现)
java·python·leetcode
Nil20813 小时前
leetcode 160相交链表
算法·leetcode·链表
ZC跨境爬虫16 小时前
LeetCode 108. 将有序数组转换为二叉搜索树(递归构建详解 + Java Python 实现)
java·python·leetcode
Tisfy16 小时前
LeetCode 3090.每个字符最多出现两次的最长子字符串:二重循环 / 滑动窗口
算法·leetcode·字符串·题解·模拟·双指针·滑动窗口
LuminousCPP17 小时前
栈和队列专题(一):LeetCode 20. 有效的括号
数据结构·经验分享·笔记·leetcode·手写栈
.道阻且长.19 小时前
8.LeetCode算法习题讲解--滑动窗口--长度最小的子数组
算法·leetcode·职场和发展
wabs66620 小时前
关于字符串【力扣541.反转字符串II的思考】
数据结构·算法·leetcode·字符串
土司大王20 小时前
LeetCode hot100——移动零
java·算法·leetcode
旖旎夜光21 小时前
LeetCode 30:串联所有单词的子串(滑动窗口) —— 题解
数据结构·c++·算法·leetcode·滑动窗口
Nil2081 天前
leetcode 48旋转图像
算法·leetcode·职场和发展