Skip to content

Instantly share code, notes, and snippets.

@imouaddine
Created November 18, 2014 16:18
Show Gist options
  • Save imouaddine/81aecb002494bdd77d81 to your computer and use it in GitHub Desktop.
Save imouaddine/81aecb002494bdd77d81 to your computer and use it in GitHub Desktop.
def find_tree_sum(start, sum)
$last_sum ||= 0
$result ||= []
if start.nil?
return false
end
$last_sum += start.value
$result << start.value
if $last_sum == sum
return $result
elsif $last_sum > sum
value = $result.delete_at($result.length - 1)
$last_sum -= value if value
elsif $last_sum < sum
if start.left.nil? && start.right.nil?
value = $result.delete_at($result.length - 1)
$last_sum -= value if value
return false
end
end
if start.left && find_tree_sum(start.left, sum)
return $result
end
if start.right && find_tree_sum(start.right, sum)
return $result
end
false
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment