Created
July 24, 2018 04:06
-
-
Save ufo2mstar/e2d664ac27706561a16aa45d66dc7e1b to your computer and use it in GitHub Desktop.
Ruby Binary Tree Print.. can also be modified to print more
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
class BinTree | |
class Node | |
attr_accessor :data, :left, :right | |
def initialize int | |
@data = int | |
end | |
def to_s | |
"Node: #{object_id}: data: #{data}" | |
"Node: #{data}" | |
end | |
end | |
attr_accessor :root | |
def initialize | |
@root = nil | |
end | |
def insert_level_order ary | |
i=0 | |
n=ary.size | |
@root = level_order_insert_util ary, i, n | |
end | |
private | |
def level_order_insert_util ary, i, n | |
if i<n | |
node = Node.new ary[i] | |
node.left = level_order_insert_util ary, (2*i)+1, n | |
node.right = level_order_insert_util ary, (2*i)+2, n | |
node | |
else | |
# recursion base case: dont run for out of bound nodes | |
# puts "#{i}, #{n}" | |
end | |
end | |
end | |
class BinTree | |
TAIL_STR = "└─" | |
FORK_STR = "├─" | |
PAD_STR = "│ " | |
INDENT_STR = " " | |
def show_tree | |
str_builder = [] | |
walk_tree_str @root, true, "", str_builder | |
puts "\n#{str_builder.join("\n")}\n" | |
end | |
private | |
def walk_tree_str node, is_tail_node, prefix, str_builder | |
str_builder << "#{prefix} #{is_tail_node ? TAIL_STR : FORK_STR} #{node}" | |
child_prefix_str = "#{prefix} #{is_tail_node ? INDENT_STR : PAD_STR}" | |
if node.left and node.right | |
walk_tree_str node.left, false, "#{child_prefix_str} L", str_builder | |
walk_tree_str node.right, true, "#{child_prefix_str} R", str_builder | |
else | |
walk_tree_str node.left, true, "#{child_prefix_str} L", str_builder if node.left | |
walk_tree_str node.right, true, "#{child_prefix_str} R", str_builder if node.right | |
end | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment