Last active
August 29, 2015 14:10
-
-
Save shelling/9b232ae03ffcaa73c4a8 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
#!/usr/bin/env ruby | |
class Node | |
attr_accessor :data, :left, :right | |
def initialize(data, left = nil, right = nil) | |
@data = data | |
@left = left | |
@right = right | |
end | |
def self.from_array(array) | |
array ? self.new(array.shift, from_array(array.shift), from_array(array.shift)) : nil | |
end | |
def inspect | |
"[#{data}, #{left.inspect}, #{right.inspect}]" | |
end | |
end | |
data = [30, | |
[20, | |
[10, [5], [15]], | |
[25, nil, [28]]], | |
[40, | |
[35], | |
[50, [41]]]] | |
tree = Node.from_array(data) | |
def print_edge(tree) | |
puts(tree.data) | |
print_left_edge(tree.left) | |
print_right_edge(tree.right) | |
end | |
def print_left_edge(tree) | |
return unless tree | |
puts(tree.data) | |
print_left_edge(tree.left) | |
print_end(tree.right) | |
end | |
def print_right_edge(tree) | |
return unless tree | |
print_end(tree.left) | |
print_right_edge(tree.right) | |
puts(tree.data) | |
end | |
def print_end(tree) | |
return unless tree | |
if !tree.left && !tree.right | |
puts tree.data | |
end | |
print_end(tree.left) | |
print_end(tree.right) | |
end | |
print_edge(tree) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment