Created
June 21, 2021 21:55
-
-
Save earlonrails/17fa49be75d8756106757aab4aca4ce8 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
#!/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