Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Perl

Idiom #17 Create a Tree data structure

The structure must be recursive. A node may have zero or more children. A node has access to its children nodes, but not to its parent.

my $tree = {
           'Root' => {
                 'Child1' => {
                       'GrandChild1' => {},
                       'GrandChild2' => {}
                 },
                 'Child2' => {}
           }
};

The natural way to create a tree in perl is using hash references.

To add a new item:

$tree->{Root}->{Child2}->{GrandChild3} = {};
typedef struct node_s
{
    int value;
    struct node_s *nextSibling;
    struct node_s *firstChild;
} node_t;

New implementation...