-
-
Save perigrin/58c688577b8cba24181094c1c8d132c4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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