-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarytree.rb
More file actions
39 lines (37 loc) · 845 Bytes
/
binarytree.rb
File metadata and controls
39 lines (37 loc) · 845 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
require "ruby-graphviz"
class TreeNode
attr_accessor :val, :left, :right
def initialize(val)
@val = val
@left = nil
@right = nil
end
end
# @param {TreeNode} root
# @return void
def drawTree(root)
if root == nil
puts "Empty tree"
return
end
g = GraphViz::new(:G, :type => :digraph)
# Level order traversal
parents = Queue.new
parents.push(root)
while !parents.empty?
cur = parents.pop
pnode = g.add_nodes(cur.val.to_s)
if cur.left != nil
parents.push(cur.left)
# add an edge from pnode to left
leftchild = g.add_nodes(cur.left.val.to_s)
g.add_edges(pnode, leftchild)
end
if cur.right != nil
parents.push(cur.right)
rightchild = g.add_nodes(cur.right.val.to_s)
g.add_edges(pnode, rightchild)
end
end
g.output(:png => "#{$0}.png")
end