adamcrussell (adamcrussell) wrote,
adamcrussell
adamcrussell

A Simple Binary Tree in Perl

This Binary Tree implementation uses Class::Struct and only defines find() and insert() operations, along with a simple print function for debugging purposes.

EDIT: The code was given some minor style updates based on Mark Gardner's feedback in the Perl Computer Science Discord Server. Please do join if you are interested in exploring Computer Science topics via a Perl lens!

package Tree129{
    use boolean;  
    use Class::Struct; 

    package Node{
        use boolean;  
        use Class::Struct; 
        struct(
            value => q/$/,
            left_child => q/Node/,
            right_child => q/Node/
        );  
        true; 
    }  
   
    struct(
        root => q/Node/
    );   

    sub print_tree{
        my($self, $node) = @_; 
        $node = $self->root() if !$node;
        if($node->left_child()){
            print $node->value() . "->" . $node->left_child()->value() . "\n";  
        } 
        if($node->right_child()){
            print $node->value() . "->" . $node->right_child()->value() . "\n";  
        } 
        else{
            print $node->value() . "\n";   
        } 
        $self->print_tree($node->left_child()) if $node->left_child;   
        $self->print_tree($node->right_child()) if $node->right_child;   
    }  

    sub find{
        my($self, $value, $node) = @_; 
        return undef if !$self->root(); 
        $node = $self->root() if !$node;
        return $node if $node->value() == $value; 
        if($value <= $node->value()){
            return $node if !$node->left_child();
            $self->find($value, $node->left_child()); 
        }  
        elsif($value >= $node->value()){
            return $node if !$node->right_child();
            $self->find($value, $node->right_child()); 
        }  
    }  

    sub insert{
        my($self, $value) = @_;  
        my $node = $self->find($value);  
        if(!$node){      # new root  
            $self->root(new Node(value => $value));  
        }   
        elsif($value < $node->value()){
            $node->left_child(new Node(value => $value));   
        } 
        elsif($value > $node->value()){
            $node->right_child(new Node(value => $value));   
        } 
        else{
            print "$value is already in the tree\n"; 
        }   
    }  
    true; 
}

package main{
    my $tree = new Tree129(); 
    $tree->insert(6); 
    $tree->insert(4); 
    $tree->insert(8); 
    $tree->insert(3); 
    $tree->insert(5); 
    $tree->insert(7); 
    $tree->insert(9);
    $tree->print_tree(); 
} 
Tags: binary tree, data structures, perl, perl programming
Subscribe

Recent Posts from This Journal

Comments for this post were disabled by the author