404. Sum of Left Leaves
# Easy
Two methods:
Use
stack<node, is_left>
, while loop, very straight forwardUse recursive, but is harder
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
# edge case
if root == None:
return 0
# regular case
if root.left == None:
return self.sumOfLeftLeaves(root.right)
if root.left.left == None and root.left.right == None:
return root.left.val + self.sumOfLeftLeaves(root.right)
return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
# edge case
if root == None:
return 0
# regular case
stack = [(root, False)]
result = 0
while len(stack) != 0:
root, is_left = stack.pop()
if root.left == None and root.right == None and is_left:
result = result + root.val
if root.left != None:
stack.append((root.left, True))
if root.right != None:
stack.append((root.right, False))
return result
Last updated
Was this helpful?