카테고리 없음

404. Sum of Left Leaves

Leeter 2021. 11. 4. 10:44

Description:

Given the root of a binary tree, return the sum of all left leaves.

# 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

'''
[1] recursive)

idea::
if cur_node.left is leaf, add left.val to output.
else return recursive function(left)+recursive function(right)

code::
(below)

-T/C: O(n)
-S/C: O(h) # function stack
'''

class Solution:
    def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        
        if self.isLeaf(root.left):
            return root.left.val+self.sumOfLeftLeaves(root.right)
        
        return self.sumOfLeftLeaves(root.left)+self.sumOfLeftLeaves(root.right)
        
        
    def isLeaf(self,root):
        if not root:
            return False
        if not root.left and not root.right:
            return True
        return False