Is there a good way to visually represent the binary search tree in Mac terminal?

For the binary search tree project in the Ruby course I changed the inspect method to this:

def inspect
“{#{@data.to_s} : #{left.inspect} | #{right.inspect}}”
end

But it’s still difficult to follow:

#<Binary_Search_Tree:0x00007ffd83910568 @array=[1, 2, 3, 4, 5], @root={3 : {2 : {1 : nil | nil} | { : nil | nil}} | {5 : {4 : nil | nil} | { : nil | nil}}}>

Does anyone have a better #inspect or #to_s method?

Try reading through this https://medium.com/derek-gc/binary-tree-traversal-breath-first-ruby-52ccab8b6597

He has a pretty print function you could modify.

Thanks for the reply Austin! It’s not quite what I am looking for but I appreciate it.

He’s outputting his tree traversal as so:

puts “loop_traverse_right:”
puts output.join(" ")
end

so he’s creating an array and then joining them together for a final output:

9 8 7 6 5 4 3 2 1

I am looking for something to visually show the tree “structure” in the terminal output so I can easily see parent-child node relationships.

If anyone finds this post in the future, this is method you want:

def pretty_print(node = root, prefix="", is_left = true)
pretty_print(node.right, "#{prefix}#{is_left ? "│ " : " “}”, false) if node.right
puts "#{prefix}#{is_left ? "└── " : "┌── “}#{node.data.to_s}”
pretty_print(node.left, "#{prefix}#{is_left ? " " : "│ “}”, true) if node.left
end