Sum of left children — Preorder traversal

    3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
# 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
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
# 3:39 pm
# a leaf is the one with no children
# is must be linked from a parent? not in the case of a root.

# we can do a inorder traversal, skip all processing of the right and top nodes.
# we all all the leaves except the last one.
self.res = []

def inorder(root, child):
if root:
if root.left:
inorder(root.left, "l")
if root.right:
inorder(root.right, "r")

if not root.left and not root.right and child == "l" :
self.res += [root.val]

inorder(root, "")
return sum(self.res)
# 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
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
# 3:39 pm- 3:56 pm
# a leaf is the one with no children
# is must be linked from a parent? not in the case of a root.

# we can do a inorder traversal, skip all processing of the right and top nodes.
# we all all the leaves except the last one.


def preorder(root, is_left):
if not root:
return 0

if not root.left and not root.right:
return root.val if is_left else 0

return preorder(root.left, True) + preorder(root.right, False)

return preorder(root, False)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store