LeetCode: Sum of Left Leaves
Find the sum of all left leaves in a given binary tree.
#Two key points to note here: Left branch and Leaf nodes
# 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 __init__(self):
self.sumLeft = 0 # declare a global variable to account for the sum of left branches
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.findLeftSum(root)
#print 'sum: ', self.sumLeft
return self.sumLeft
def findLeftSum(self, node, dir=None):
#////////////////////////////////
# do it using in-order traversal
#////////////////////////////////
if node is None:
return 0
# Only sum those node vals when the dir = 0 (signifying left branch) and
# it has no more child nodes
if dir == 0 and node.left is None and node.right is None:
self.sumLeft += node.val
# When left node is pushed to the stack, pass it's identifier direction as 0
self.findLeftSum(node.left, 0)
#print 'node val: ', node.val
self.findLeftSum(node.right, 1)
Find the sum of all left leaves in a given binary tree.
3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively.
Return 24.
#Two key points to note here: Left branch and Leaf nodes
# 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 __init__(self):
self.sumLeft = 0 # declare a global variable to account for the sum of left branches
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.findLeftSum(root)
#print 'sum: ', self.sumLeft
return self.sumLeft
def findLeftSum(self, node, dir=None):
#////////////////////////////////
# do it using in-order traversal
#////////////////////////////////
if node is None:
return 0
# Only sum those node vals when the dir = 0 (signifying left branch) and
# it has no more child nodes
if dir == 0 and node.left is None and node.right is None:
self.sumLeft += node.val
# When left node is pushed to the stack, pass it's identifier direction as 0
self.findLeftSum(node.left, 0)
#print 'node val: ', node.val
self.findLeftSum(node.right, 1)
No comments:
Post a Comment