#!/usr/bin/perl use strict; use warnings; use Data::Dumper; package BinTree; use Moose; with 'RoleDigraph'; use overload '""' => \&to_s; has 'val' => ( is => 'rw', isa => 'Num' ); has 'l' => ( is => 'rw'); has 'r' => ( is => 'rw'); sub _set_l { my $self = shift; my $val = shift; if (blessed $self->l) { $self->l->append($val); } else { $self->l($self->new(val => $val)); } } sub _set_r { my $self = shift; my $val = shift; if (blessed $self->r) { $self->r->append($val); } else { $self->r($self->new(val => $val)); } } sub to_s { my $self = shift; my $v = $self->val; my $l = blessed $self->l ? $self->l->to_s : undef; my $r = blessed $self->r ? $self->r->to_s : undef; return join ', ', grep defined, ($l, $v, $r); } sub append { my $self = shift; my @vals = @_; while ( my $n = shift @vals ) { if ($n < $self->val) { $self->_set_l($n) } elsif ($n > $self->val) { $self->_set_r($n) } } } sub _as_queque { my $self = shift; my $queque = shift || []; my $v = $self->val; if (blessed $self->l) { push @$queque, [$v, $self->l->val]; $self->l->_as_queque($queque); } if (blessed $self->r) { push @$queque, [$v, $self->r->val]; $self->r->_as_queque($queque); } return $queque, } package main; my @list = (20, 4, 28, 9, 100, 12, 84, 10, 11); my $tree = BinTree->new( val => shift @list ); $tree->append(@list); $tree->append(1, 50, 200); print $tree . "\n" x 2; print $tree->as_digraph;