Skip to content

Commit ba63a52

Browse files
authored
Update tree.rb
1 parent 90c9153 commit ba63a52

File tree

1 file changed

+20
-9
lines changed
  • contents/tree_traversal/code/ruby

1 file changed

+20
-9
lines changed

contents/tree_traversal/code/ruby/tree.rb

+20-9
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,18 @@ def create_tree(rows, children)
33

44
{
55
id: rows,
6-
children: Array.new(3, create_tree(rows - 1, children))
6+
children: Array.new(children, create_tree(rows - 1, children))
77
}
88
end
99

1010
def dfs_preorder(tree)
11-
puts tree[:id]
11+
print "#{tree[:id]} "
1212
tree[:children].each { |child| dfs_preorder(child) }
1313
end
1414

1515
def dfs_postorder(tree)
1616
tree[:children].each { |child| dfs_postorder(child) }
17-
puts tree[:id]
17+
print "#{tree[:id]} "
1818
end
1919

2020
def dfs_inorder(tree)
@@ -24,16 +24,16 @@ def dfs_inorder(tree)
2424
raise 'Postorder traversal is only valid for binary trees'
2525
end
2626

27-
dfs_inorder(tree.children[0])
28-
puts tree[:id]
29-
dfs_inorder(tree.children[1])
27+
dfs_inorder(tree[:children][0])
28+
print "#{tree[:id]} "
29+
dfs_inorder(tree[:children][1])
3030
end
3131

3232
def dfs_iterative(tree)
3333
stack = [tree]
3434
while stack.count.positive?
3535
current = stack.pop
36-
puts current[:id]
36+
print "#{current[:id]} "
3737
stack.push(*current[:children])
3838
end
3939
end
@@ -42,13 +42,24 @@ def bfs(tree)
4242
queue = [tree]
4343
while queue.count.positive?
4444
current = queue.shift
45-
puts current[:id]
45+
print "#{current[:id]} "
4646
queue.push(*current[:children])
4747
end
4848
end
4949

50-
root = create_tree(3, 3)
50+
root = create_tree(2, 3)
51+
puts "[#]\nRecursive DFS:"
5152
dfs_preorder(root)
53+
puts ""
54+
puts "[#]\nRecursive Postorder DFS:"
5255
dfs_postorder(root)
56+
puts ""
57+
puts "[#]\nStack-based DFS:"
5358
dfs_iterative(root)
59+
puts ""
60+
puts "[#]\nQueue-based DFS:"
5461
bfs(root)
62+
puts ""
63+
root_binary = create_tree(3, 2);
64+
puts "[#]\nRecursive Inorder DFS for Binary Tree:"
65+
dfs_inorder(root_binary)

0 commit comments

Comments
 (0)