But now say if third value that is generated is 80 . At this point in time $root still points to the orignal tree with value 40.
Now because $root is already defined it skips to the if else condition , and makes a call that 80 > 40 , hence it should be inserted to the right
But $tree->{Right} is already defined , and it contains the value 60, so it never executes the actual routine to create a reference to a new tree
Yes, $tree->{Right} is already defined, so it recurses again, and inserts 80 as the right son of 60.
($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord
}map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
| [reply] [d/l] [select] |
( I understand till here) But now say if third value that is generated is 80 . At this point in time $root still points to the orignal tree with value 40.
Now because $root is already defined it skips to the if else condition , and makes a call that 80 > 40 , hence it should be inserted to the right
But $tree->{Right} is already defined , and it contains the value 60, so it never executes the actual routine to create a reference to a new tree .....
Follow what is happening:
- and makes a call that 80 > 40 , hence it should be inserted to the right
Yes. So it calls the insert function on the right tree. When entering this new function call, it finds a node where the value is 60. It compares the values, and since 80 is larger than 60, it sees that it should call the insert function recursively once more on the right side. When it gets to this next level, the node below 60 does not exists yet, so that insert can actually create the node 80 below (and right of) node 60.
Update ( Dec 06, 2015 at 22:25 UTC):
This graph may make it clearer:
40
/ \
/ \
60
/ \
\
80
Now, if you add another node with a value of 50, it will go right of 40 and then left of 60:
40
/ \
/ \
60
/ \
/ \
50 80
Update 2:
And, since you appear not to have seen my earlier warning, let me repeat that the link you're giving on the O'Reilly books is on a site (presumably in Ukraine) which most probably does not have the right to publish these contents on the Internet. In other words, it is most probably illegal, and I would advise again you to update your original post and remove the link.
| [reply] [d/l] [select] |
Thanks for the response. I see that the link has been removed. Going forward I will keep this in mind.
| [reply] |
Hello ,
How can I do a Breadth First search for a binary tree in perl ?
For the above code how can I go ahead and create a subroutine for Breadth First search ?
For a breadth first search , since I have to visit the left node first and then the right node and then repeat this process till I reach the very end , I fee its sort of tricky...
I have written a snippet below for "Depth First" search , but not able to think for a Breadth first search
sub depthFirst {
my ($tree) =@_;
return unless ($tree);
print $tree->{Value};
depthFirst($tree->{Left});
depthFirst($tree->{Right});
}
| [reply] [d/l] |