Skip to content

Instantly share code, notes, and snippets.

@perigrin
Created Sep 12, 2021
Embed
What would you like to do?
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