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
class Node | |
attr_accessor :left, :right, :depth, :name | |
def initialize(depth, name) | |
@depth = depth | |
@name = name | |
end | |
end | |
def traverse(node, k, depth=0) | |
return if k < 0 |
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
# method: flatten_array | |
# arguments: an unflattened array, and output array, initially set to []. | |
# output: a flattened array, so that arbitrary nesting of arrays is removed. | |
# the method employs tail recursion. It loops over each element of the array. | |
# if the current element is not an array, it adds it to the array it is building for output. | |
# but if the current element is an array, then it will call itself recursively so that the next call can iterate over this array element and add items from it recursively. | |
def flatten_array(array, start=[]) | |
array.each do |elem| |