Problems creating Binary Tree

• 07-13-2010
darren78
Problems creating Binary Tree
Hi all,

I'm doing an exercise from a book to design and draw a binary tree, with the constructor simply taking the number of levels as a constructor.

I have it creating the correct number of nodes for the required level, however I am having trouble using the module operator within the constructor.

This code works:

Code:

Binary_tree::Binary_tree(int l)
:levels(l)
{
if(levels>0)
nodes=pow(2.0, levels)-1;

for(int i = 1; i< nodes; ++i) {

}
}

The problem is I obviously want the nodes to go left/right. So I used the modulo remainder to determine if the node is odd/even as such:
Code:

Binary_tree::Binary_tree(int l)
:levels(l)
{
if(levels>0)
nodes=pow(2.0, levels)-1;

for(int i = 1; i< nodes; ++i) {
if(i%2 == 0)

}
}

However, I get a windows error box appearing saying vector subscript out of range? Any ideas?

Thanks.
• 07-13-2010
darren78
Please ignore. Have figured it out.
• 07-13-2010
laserlight
By the way, you could avoid #include <cmath> and the use of std::pow by changing:
Code:

nodes=pow(2.0, levels)-1;
to:
Code:

nodes = (1U << levels) - 1;
• 07-13-2010
darren78
Quote:

Originally Posted by laserlight
By the way, you could avoid #include <cmath> and the use of std::pow by changing:
Code:

nodes=pow(2.0, levels)-1;
to:
Code:

nodes = (1U << levels) - 1;

What does the 1U mean?

Thanks.
• 07-13-2010
laserlight
1 Unsigned.