Created
November 18, 2014 16:18
-
-
Save imouaddine/81aecb002494bdd77d81 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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