Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: How do I create a binary tree?

by Athanasius (Archbishop)
on Dec 07, 2015 at 03:11 UTC ( [id://1149552]=note: print w/replies, xml ) Need Help??


in reply to How do I create a binary tree ?

Hello punitpawar,

I am trying to write a program that will create a binary tree for any 10 random numbers that are generated.

From your later posts, it appears that you actually want a sorted binary tree. has various modules you can use for this. Here is one example:

#! perl use strict; use warnings; use Tree::Binary::Search; use Tree::Binary::Visitor::InOrderTraversal; for (1 .. 20) { my $btree = Tree::Binary::Search->new; $btree->useNumericComparison; for (1 .. 10) { my $num = int rand 100; redo if $btree->exists($num); $btree->insert($num => 1); } my $visitor = Tree::Binary::Visitor::InOrderTraversal->new; $visitor->setNodeFilter(sub { $_[0]->getNodeKey }); $btree->accept($visitor); print join(' ', map { sprintf '%2d', $_ } $visitor->getResults), " +\n"; $btree->DESTROY; }

Output:

13:09 >perl 1475_SoPW.pl 0 9 14 33 37 55 60 77 89 99 15 26 28 51 59 75 78 79 94 99 18 31 33 38 44 47 70 73 77 84 4 21 24 28 38 57 65 76 98 99 16 42 50 62 70 71 83 87 92 94 21 29 35 40 49 68 71 79 85 90 2 5 11 16 24 46 50 55 75 99 19 26 28 39 42 51 53 59 66 98 26 35 41 45 53 54 67 81 88 95 19 28 45 51 58 64 65 67 79 82 0 21 27 54 60 63 64 73 78 99 0 5 13 27 31 50 61 74 77 92 11 13 14 29 52 60 71 79 80 86 8 9 29 36 37 50 58 69 81 82 10 14 23 38 46 53 57 67 90 97 7 8 13 14 30 32 34 41 50 76 6 11 21 28 50 53 78 79 96 98 19 24 28 37 60 71 78 85 88 93 14 26 28 31 42 59 71 83 87 94 0 8 13 15 19 51 52 71 78 85 13:09 >

As you can see, in-order traversal outputs the numbers in sorted (numerical ascending) order, showing that the underlying binary tree is sorted.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1149552]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (2)
As of 2024-03-19 06:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found