( 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:
Now, if you add another node with a value of 50, it will go right of 40 and then left of 60:40 / \ / \ 60 / \ \ 80
Update 2:40 / \ / \ 60 / \ / \ 50 80
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.In reply to Re^3: How do I create a binary tree ?
by Laurent_R
in thread How do I create a binary tree ?
by punitpawar
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |