Python 5-liner iterative solution

  • 0

    Any tree traversal will do.

    def sumOfLeftLeaves(self, root):
        lvl, ans = [root] if root else [], 0
        while lvl:
            ans += sum(node.left.val for node in lvl if node.left and not (node.left.left or node.left.right))
            lvl = [child for node in lvl for child in (node.left, node.right) if child]
        return ans       

    Another one:

    def sumOfLeftLeaves(self, root):
        ans, stk = 0, []
        while stk or root:
            while root:
                root = root.left
                if root and not (root.left or root.right):
                    ans += root.val
            root = stk.pop().right
        return ans

Log in to reply

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