Skip to content

Latest commit

 

History

History
87 lines (66 loc) · 2.01 KB

0404._sum_of_left_leaves.md

File metadata and controls

87 lines (66 loc) · 2.01 KB

Navigation

Links

  1. https://leetcode.com/problems/sum-of-left-leaves
  2. https://leetcode-cn.com/problems/sum-of-left-leaves/

Solution 1 dfs 递归

    时间复杂度: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):
        if not root:
            return 0

        if root.left and not root.left.left and not root.left.right:
            return root.left.val + self.sumOfLeftLeaves(root.right)
        
        return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)

Solution 2 dfs 迭代 先序

class Solution:
    def sumOfLeftLeaves(self, root):
        if not root:
            return 0

        _sum = 0
        stack = [root]

        while stack:
            root = stack.pop()
            
            if root.left and not root.left.left and not root.left.right:
                _sum += root.left.val
            
            if root.left:
                stack.append(root.left)
            
            if root.right:
                stack.append(root.right)

        return _sum

Solution 3 bfs

from collections import deque

class Solution:
    def sumOfLeftLeaves(self, root):
        if not root:
            return 0

        _sum = 0
        queue = deque([root])

        while queue:
            root = queue.popleft()
            
            if root.left and not root.left.left and not root.left.right:
                _sum += root.left.val
            
            if root.left:
                queue.append(root.left)
            
            if root.right:
                queue.append(root.right)

        return _sum