python code, easy to understand, with explanation.


  • 0
    Z

    the idea is to collect left leaf values in a list(collector) while tree traversal.
    use a flag is_left to indicate wether it is a left node. so when a node is left node and is leaf, its value will be collected.

    P.S. mutable parameter collector seems a bad idea. can some one figure out a better way?

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def isleaf(self, node):
            if node and not node.left and not node.right:
                return True
            else:
                return False
        def traversal(self, node, collector, is_left):
            if not node:
                pass
            elif self.isleaf(node) and is_left:
                collector.append(node.val)
            else:
                self.traversal(node.left, collector, is_left=True)
                self.traversal(node.right, collector, is_left=False)
        def sumOfLeftLeaves(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            if root is None:
                return 0
            left_vals = []
            self.traversal(root, left_vals, False)
            return sum(left_vals)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.