Created
January 28, 2022 06:15
-
-
Save david50407/ded8472c979426ad4a2da8b39ddf5f50 to your computer and use it in GitHub Desktop.
This file contains 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
RubyVM::InstructionSequence.compile_option = { | |
tailcall_optimization: true, | |
trace_instruction: false | |
} | |
# 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} root1 | |
# @param {TreeNode} root2 | |
# @return {Integer[]} | |
def get_all_elements(root1, root2) | |
merge(root1 || [], root2 || []).to_a | |
end | |
def merge(array_1, array_2) | |
return enum_for(__method__, array_1, array_2) unless block_given? | |
a = array_1.each | |
b = array_2.each | |
loop { yield a.peek < b.peek ? a.next : b.next } | |
loop { yield a.next } | |
loop { yield b.next } | |
end | |
class TreeNode | |
eval <<-EOF | |
def each(&block) | |
return to_enum(:each) unless block_given? | |
# equivalent to these: recursion is suck | |
left.each(&block) unless left.nil? | |
yield val | |
right.each(&block) unless right.nil? | |
end | |
EOF | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment