Skip to content

Commit ca3f03d

Browse files
committed
Tree Height with recursion
1 parent eba43bc commit ca3f03d

File tree

1 file changed

+27
-14
lines changed

1 file changed

+27
-14
lines changed

tree_height.rb

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,38 @@
11
# https://codility.com/demo/take-sample-test/tree_height
22

33
Tree = Struct.new(:x, :l, :r)
4-
State = Struct.new(:tree, :height)
54

65
def tree_height(tree)
7-
stack = []
8-
max_height = 0
9-
10-
# traversing the tree using depth first search
11-
stack << State.new(tree, 0)
12-
while stack.any?
13-
state = stack.pop
14-
current_tree = state.tree
15-
max_height = [max_height, state.height].max
16-
stack << State.new(current_tree.l, state.height + 1) if current_tree.l
17-
stack << State.new(current_tree.r, state.height + 1) if current_tree.r
18-
end
6+
left_height = right_height = 0
7+
8+
left_height = 1 + tree_height(tree.l) if tree.l
9+
right_height = 1 + tree_height(tree.r) if tree.r
1910

20-
max_height
11+
[left_height, right_height].max
2112
end
2213

14+
# alternative solution (more complicated, but I would like to keep
15+
# it as a reference for depth first search)
16+
#
17+
# State = Struct.new(:tree, :height)
18+
#
19+
# def tree_height(tree)
20+
# stack = []
21+
# max_height = 0
22+
#
23+
# # traversing the tree using depth first search
24+
# stack << State.new(tree, 0)
25+
# while stack.any?
26+
# state = stack.pop
27+
# current_tree = state.tree
28+
# max_height = [max_height, state.height].max
29+
# stack << State.new(current_tree.l, state.height + 1) if current_tree.l
30+
# stack << State.new(current_tree.r, state.height + 1) if current_tree.r
31+
# end
32+
#
33+
# max_height
34+
# end
35+
2336
require 'minitest/autorun'
2437

2538
class Tests < MiniTest::Unit::TestCase

0 commit comments

Comments
 (0)