Skip to content

Instantly share code, notes, and snippets.

@earlonrails
Created June 21, 2021 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save earlonrails/17fa49be75d8756106757aab4aca4ce8 to your computer and use it in GitHub Desktop.
Save earlonrails/17fa49be75d8756106757aab4aca4ce8 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
Node = Struct.new(:value, :left, :right)
def create_tree(nodes, root=nil, idx=0)
if nodes.size > idx
root = Node.new(nodes[idx])
root.left = create_tree(nodes, root.left, 2 * idx + 1)
root.right = create_tree(nodes, root.right, 2 * idx + 2)
end
return root
end
require 'minitest/autorun'
describe 'create_tree' do
it "should create a binary tree from an array" do
arr = [1, 2, 3, 4, 5, 6]
root = create_tree(arr)
root.value.must_equal(1)
root.left.value.must_equal(2)
root.right.value.must_equal(3)
root.left.left.value.must_equal(4)
root.left.right.value.must_equal(5)
root.right.left.value.must_equal(6)
assert_nil(root.right.right)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment