Skip to content

Instantly share code, notes, and snippets.

@perigrin
Created September 12, 2021 00:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save perigrin/58c688577b8cba24181094c1c8d132c4 to your computer and use it in GitHub Desktop.
Save perigrin/58c688577b8cba24181094c1c8d132c4 to your computer and use it in GitHub Desktop.
use 5.24.0; # implies strict, say, postderef
use Object::Pad; # implies strict, warnings, and signatures
no warnings qw{ experimental };
class CorNode {
has $value :param :mutator = 0 ;
has $parent :param :mutator = undef;
has $left :param = undef;
has $right :param = undef;
# could possibly replace with a method modifier
method left ( $node = undef ) {
if ( defined $node ) {
$left = $node;
$node->parent($self);
}
return $left
}
# could possibly replace with a method modifier
method right ( $node = undef ) {
if ( defined $node ) {
$right = $node;
$node->parent($self);
}
return $right
}
method is_root () { return !defined $parent }
method is_leaf () { return !defined($left // $right) }
method depth () {
my $depth = 0;
my $copy = $self;
while ( !$copy->is_root ) {
$depth++;
$copy = $copy->parent;
}
return $depth;
}
}
my %nodes = map { $_ => CoreNode->new(value => $_) } (1..9);
for my $i (1..3) {
$nodes{$i}->left = $nodes{$i * 2};
$nodes{$i}->right = $nodes{$i * 2 + 1};
}
$nodes{4}->left = $nodes{8};
$nodes{6}->right = $nodes{9};
my $x = <<'END';
0 1
/ \
1 2 3
/ \ / \
2 4 5 6 7
/ \
3 8 9
END
say $x;
say join "\t", '>>>>', qw{ Value Root RorP LorD Leaf Depth }, '<<<<';
for my $n ( sort keys %nodes ) {
say join "\t ",
'>>>',
$nodes{$n}->value,
$nodes{$n}->is_root,
( $nodes{$n}->is_root ? 'R' : $nodes{$n}->parent->value ),
(
$nodes{$n}->is_leaf
? 'L'
: join ' + ',
defined $nodes{$n}->left ? $nodes{$n}->left->value : '_',
defined $nodes{$n}->right ? $nodes{$n}->right->value : '_',
),
$nodes{$n}->is_leaf,
$nodes{$n}->depth,
'<<<';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment