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,


In reply to Re: How do I create a binary tree? by Athanasius
in thread How do I create a binary tree ? by punitpawar

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.