Solution Using DFS


  • 0
    Y

    Using DFS to traversal the tree and if the node is left leaf, add the value to result.

    class Solution(object):
        def sumOfLeftLeaves(self, root):
            result = [0]
            self.dfs(root, result, False)
            return result[0]
        
        # Use left to mark whether the current node is left child  
        def dfs(self, root, result, left):
            if root is None:
                return
            else:
                # If the node is left leaf, add the value to the result
                if root.left is None and root.right is None and left:
                    result[0] += root.val
                else:
                    self.dfs(root.left, result, True)
                    self.dfs(root.right, result, False)
                return
    

Log in to reply
 

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