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.
# Definition for a binary tree node.
# class TreeNode
# attr_accessor :val, :left, :right
# def initialize(val = 0, left = nil, right = nil)
# @val = val
# @left = left
# @right = right
# end
# end
# @param {TreeNode} root
# @return {Integer}
def sum_of_left_leaves(root)
@sum = 0
cal(root, false)
p @sum
end
def cal(node, is_left_node)
return if node.nil?
@sum += node.val if is_left_node && node.left.nil? && node.right.nil?
cal(node.left, true)
cal(node.right, false)
end