|
1 | 1 | # https://codility.com/demo/take-sample-test/tree_height
|
2 | 2 |
|
3 | 3 | Tree = Struct.new(:x, :l, :r)
|
4 |
| -State = Struct.new(:tree, :height) |
5 | 4 |
|
6 | 5 | 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 |
19 | 10 |
|
20 |
| - max_height |
| 11 | + [left_height, right_height].max |
21 | 12 | end
|
22 | 13 |
|
| 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 | + |
23 | 36 | require 'minitest/autorun'
|
24 | 37 |
|
25 | 38 | class Tests < MiniTest::Unit::TestCase
|
|
0 commit comments