題目
Find the sum of all left leaves in a given binary tree.
Example:
3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
方法
遞歸遍歷,如果為左節(jié)點值漫,則打上標記isLeft
猛铅,如果該節(jié)點沒有左右子節(jié)點峻村,則將該節(jié)點值累加到最后的結果中
python代碼
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def sumOfLeftLeaves(self, root):
self.result = 0
self.traverse(root)
return self.result
def traverse(self, node, isLeft=False):
if node and node.left == None and node.right == None and isLeft:
self.result += node.val
if node:
self.traverse(node.left, True)
self.traverse(node.right)
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(7)
assert Solution().sumOfLeftLeaves(root) == 24