1
exercism fetch perl5 binary-search-tree

binary_search_tree.t

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/usr/bin/env perl
use warnings;
use strict;

use Test::More;
use FindBin;
my $dir;
BEGIN { $dir = $FindBin::Bin . '/' };
use lib $dir;

my $module = $ENV{EXERCISM} ? 'Example' : 'BinarySearchTree';

use_ok($module) or BAIL_OUT "You need to create a module called $module.pm";

sub new_bst {
  no strict 'refs';
  $module->new(@_);
}

for (1) {
  is new_bst(4)->data, 4, 'data is retained';
}

for (1) {
  my $bst = new_bst(4);
  $bst->insert(4);
  is $bst->data, 4, 'inserting same';
  is $bst->left->data, 4, 'inserting same';
}

for (1) {
  my $bst = new_bst(4);
  $bst->insert(2);
  is $bst->data, 4, 'inserting less';
  is $bst->left->data, 2, 'inserting less';
}

for (1) {
  my $bst = new_bst(4);
  $bst->insert(5);
  is $bst->data, 4, 'inserting more';
  is $bst->right->data, 5, 'inserting more';
}

for (1) {
  my $bst = new_bst(4);
  $bst->insert($_) for 2, 6, 1, 3, 7, 5;

  is $bst->data, 4, 'complex tree';
  is $bst->left->data, 2, 'complex tree';
  is $bst->left->left->data, 1, 'complex tree';
  is $bst->left->right->data, 3, 'complex tree';
  is $bst->right->data, 6, 'complex tree';
  is $bst->right->left->data, 5, 'complex tree';
  is $bst->right->right->data, 7, 'complex tree';
}

sub record_all_data($) {
  my $bst = shift;
  my $all_data = [];

  $bst->each(sub {
    my $data = shift;
    push @$all_data, $data;
  });

  return $all_data;
}

for (1) {
  my $bst = new_bst(4);
  is_deeply record_all_data $bst, [4], 'iterating one element';
}

for (1) {
  my $bst = new_bst(4);
  $bst->insert(2);
  is_deeply record_all_data $bst, [2, 4], 'iterating over smaller element';
}

for (1) {
  my $bst = new_bst(4);
  $bst->insert(5);
  is_deeply record_all_data $bst, [4, 5], 'iterating over larger element';
}

for (1) {
  my $bst = new_bst(4);
  $bst->insert($_) for 2, 6, 1, 3, 7, 5;

  is_deeply record_all_data $bst, [1 .. 7], 'iterating over complex tree';
}

done_testing;