Question

Implement a complete binary tree using an array

Asked by: jamesreddy

Ok.  I am willing to post a second 500 pointer to anyone who can assist me here.  I am a C++ dummy, so be kind.  I am trying to convert an algorithm from VB6 to C++, but I don't know where to start.  C++ is WAY out of my league.

Anyway...I have a program in VB that does the assigned task (an old homework problem from my VB classes, but is right along the same lines as what I'm trying to accomplish in C++).

The program performs a binary tree sort using an array.  The treesize is only 10, and the values will change from time to time, but for the moment let's assume the nodes are initialized as follows:

treenodes[0]=3;
treenodes[1]=2;
treenodes[2]=23;
treenodes[3]=9;
treenodes[4]=5;
treenodes[5]=14;
treenodes[6]=21;
treenodes[7]=13;
treenodes[8]=17;
treesize=10; //as mentioned above


I need to have a program that'll utilize the int parent, int leftchild, and int rightchild to organize these ten values.  This is so vastly different from VB6 that I don't even know where to start.

I am trying to teach myself C++ and I'm using my VB code as a guideline to write C++ code.  Can anyone get me the source code that can perform this function?  Our C++ instructor for the college I work at recently had a heart attack, and is in the hospital and out of commission for a while.  They threw me into this position to "sub" for him being that I am the only other instructor with any background in programming....unfortunately, just the wrong kind (SQL and VB6).  Further...I am a networking guru.  I have tried adamantly to AVOID programming.  LOL.  Now, here I am...knee deep in it.

I've scoured the net and found a lot of code on arrays and BSTs, but can't really find one that will show me how to create a binary tree sort using an array.  I've got to sub for this guy for up to the next six weeks (unless the college can find a temp substitute sooner), so I am hoping someone here can help me out from time to time when I need it.

Thanks in advance!

James

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-08-28 at 21:16:14ID21111174
Tags

tree

,

binary

Topic

C++ Programming Language

Participating Experts
3
Points
500
Comments
11

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Help Binary Search Tree
    Please (if you are able to) write a program thaty maintains information on NHL hockey teams as a double binary search tree. The main tree should hold the names of the teams, while the sub-tree holds the names of the players.(See diasgram below) Canadiens / | ...
  2. Balancing a binary search tree
    Is there a way to balance a binary search tree (not AVL tree, not red-black tree or anything other then BST) without reading all its content and then rebuilding it from the sorted list of values ?
  3. Binary tree or N-Tree algorithms
    Hai, If any one has done before on a binary tree or Ntree Algorithms, please guide as how to create functions and classes in php. Hope u can get details regarding what is a tree like that in data structures and algorithms.. Expecting helps from all masterminds in php as w...
  4. binary tree
    how do i print a binary tree inorder

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: avizitPosted on 2004-08-28 at 22:30:18ID: 11924488

Binary Trees are trees where every node has at most 2 child. The left child and the right child
So to implement a binary tree as an array

you take array[0] as the root of the binary tree

and its two child are  array[1] , --left child
                               array[2]  - right child


similarly array[1] as two child  left-> array[3] and right -> array[4]

so basically each node "i" has two children  the left child is array[2i +1 ] and right child is array[2i +2 ]

now you have to sort the binary tree

for representation also read "Arrayed Binary Trees" in http://www.gamedev.net/reference/programming/features/trees2/page2.asp

   

 

by: avizitPosted on 2004-08-28 at 22:34:58ID: 11924498

for sorting  you have to convert the binary tree into a heap
the theory part is quite lengthy to type here so i will just give a link

http://www.maths.abdn.ac.uk/~igc/tch/mx4002/notes/node60.html

teh sorting algorithm is explained in

http://www.iti.fh-flensburg.de/lang/algorithmen/sortieren/heap/heapen.htm  with a java implementation .

 

by: jamesreddyPosted on 2004-08-28 at 23:02:42ID: 11924534

While I appreciate the links, my problem is simply this...none of it makes sense to me yet.  I am at a complete loss at how to do this having no background in C++.  Can you supply the code and/or supply a link that can show me exactly how to write this out?  I understand the PREMISE of a binary tree sort and array, but the code is completely out of my league.  These students have a project due by Monday and I'm hoping that I can have the answer by then.  How do I write a binary tree sort using an array that will organize ten values such as the ones I have listed above?

This whole C++ thing has caught me completely off guard.

James

 

by: rstaveleyPosted on 2004-08-29 at 00:52:14ID: 11924787

You've been put into an impossible possition, which sounds very stressful. I'm sure it would be more valuable for the students if you taught them about networking instead. Alternatively, you need to change the format of your teaching to allow students to work through the problems and act as a kind of facilitator. Asking for lecture notes from EE the day before each lecture certainly won't cut the mustard. Good luck.

 

by: avizitPosted on 2004-08-29 at 01:02:20ID: 11924800

plus telling bout heap and heapsort is going to be a bit difficult without being able to draw diagrams etc
hence i provided the link which had diagrams.

 

by: jamesreddyPosted on 2004-08-29 at 05:59:05ID: 11925463

It's not an impossible position.  I just need someone to supply me with some code that can help me correct this project.  I need some basis to know if the students did this correctly so I can correct the work.  I'm just the fill-in until we get someone who can understand this stuff.  How hard can this be?  I can do it in VB easily.  Is C++ really that much more complicated?

 

by: jamesreddyPosted on 2004-08-29 at 06:44:43ID: 11925601

Ok...I don't know if this will help.  Here is a code in VB that performs a similar function (from my old class I took bak in college).  I don't know if anyone knows VB in here, but how can I convert this to C++?

===========================================
BEGIN
  MultiUse = -1  'True
  Persistable = 0  'NotPersistable
  DataBindingBehavior = 0  'vbNone
  DataSourceBehavior  = 0  'vbNone
  MTSTransactionMode  = 0  'NotAnMTSObject
END
Attribute VB_Name = "clsHeap"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Explicit

Private Type HeapItem
    Key As Variant
    Data As Variant
End Type

Dim Items() As HeapItem
Dim lSize As Long ' Number of items in the heap
Public Property Get Count() As Long
    Count = lSize
End Property

Private Sub RebuildHeap(ByVal Root As Long)
   
    Dim ChildIndex As Long
    Dim RightChildIndex As Long

    ChildIndex = 2 * Root + 1 ' Index of root's left child, if any
   
    If ChildIndex < lSize Then

        RightChildIndex = ChildIndex + 1 ' Index of right child, if any.

        If (RightChildIndex < lSize) And (Items(RightChildIndex).Key > Items(ChildIndex).Key) Then
            ChildIndex = RightChildIndex ' Index of larger child
        End If
       

        If Items(Root).Key < Items(ChildIndex).Key Then
            Dim Temp As HeapItem
            Temp = Items(Root)
            Items(Root) = Items(ChildIndex)
            Items(ChildIndex) = Temp

            RebuildHeap ChildIndex
        End If
    End If
       
End Sub

Public Function Remove() As Variant

    If lSize > 0 Then
        Remove = Items(0).Data
        lSize = lSize - 1
        Items(0) = Items(lSize)
        RebuildHeap 0
        ReDim Preserve Items(lSize)
    Else
        Remove = Empty ' Heap empty
    End If
End Function


Public Sub Add(ByVal Key As Variant, ByVal Data As Variant)

    ReDim Preserve Items(lSize) ' Make room for the new item.
    Items(lSize).Key = Key
    Items(lSize).Data = Data
   
    Dim Place As Long, Parent As Long
    Place = lSize
    Parent = (Place - 1) / 2
   
    Do While Parent >= 0 And (Items(Place).Key > Items(Parent).Key)
        ' swap Items(Place) and Items(Parent)
        Dim Temp As HeapItem
        Temp = Items(Parent)
        Items(Parent) = Items(Place)
        Items(Place) = Temp
       
        Place = Parent
        Parent = (Place - 1) / 2
    Loop
    lSize = lSize + 1
End Sub
===========================================

It's not exactly what these students are doing, but it's close enough for government work.  How can I perform the same function in C++?  I already understood I'd need to build a heap and what not, but after that....the code is where I'm dead.  C++ is so different....or is it?  I don't know.  Everywhere I've looked online suggest that C++ is more complicated.  While I can read code that I find online and guess at what it does, I cannot formulate it on my own.

In any event...if this is too complicated, then tell me.  I'm trying to have something for these guys this week.

James

 

by: avizitPosted on 2004-08-29 at 09:20:09ID: 11926137

go to link http://www.fortunecity.com/skyscraper/false/780/proj.html

if you scroll down you have a link for a cpp program for heapsort using arrays for heaps.

the link to the program is

http://www.fortunecity.com/skyscraper/false/780/files/heapsort.cpp

 

by: DanRollinsPosted on 2004-08-29 at 11:34:01ID: 11926625

Here is a litteral translation of your VB code into roughly-equivallent C++

//Private Type HeapItem
//    Key As Variant
//    Data As Variant
//End Type

//Dim Items() As HeapItem
//Dim lSize As Long ' Number of items in the heap
//Public Property Get Count() As Long
//    Count = lSize
//End Property


typedef struct {
      int nKey;   // the value that will indicate order
      int nData;  // the value that will be sorted
} HeapItem;

#define CNUM_MaxSize 100

HeapItem garItems[CNUM_MaxSize];  // for simplicity, let the array have 100 items
int      gnSize= 0;               // make make both of these global variables

//Private Sub RebuildHeap(ByVal Root As Long)
//    Dim ChildIndex As Long
//    Dim RightChildIndex As Long
//    ChildIndex = 2 * Root + 1 ' Index of root's left child, if any
//    If ChildIndex < lSize Then
//        RightChildIndex = ChildIndex + 1 ' Index of right child, if any.
//        If (RightChildIndex < lSize) And (Items(RightChildIndex).Key > Items(ChildIndex).Key) Then
//            ChildIndex = RightChildIndex ' Index of larger child
//        End If
//        If Items(Root).Key < Items(ChildIndex).Key Then
//            Dim Temp As HeapItem
//            Temp = Items(Root)
//            Items(Root) = Items(ChildIndex)
//            Items(ChildIndex) = Temp
//            RebuildHeap ChildIndex
//        End If
//    End If
//End Sub

void RebuildHeap( int nRootIdx )
{
      int nChildIdx;
      int nRightChildIdx;

      nChildIdx= (2 * nRootIdx) + 1; // Index of root's left child, if any
      if ( nChildIdx < gnSize ) {
            nRightChildIdx = nChildIdx + 1;   // Index of right child, if any.
            if ( (nRightChildIdx < gnSize) && (garItems[nRightChildIdx].nKey > garItems[nChildIdx].nKey) ) {
                  nChildIdx= nRightChildIdx; //  ' Index of larger child
            }
            if ( garItems[nRootIdx].nKey < garItems[ nChildIdx].nKey ) {
                  HeapItem rTemp= garItems[ nRootIdx];
                  garItems[ nRootIdx]= garItems[ nChildIdx];
                  garItems[ nChildIdx]= rTemp;
                  RebuildHeap( nChildIdx ); // recursive call to "sort from here"
            }
      }
}


//Public Function Remove() As Variant
//    If lSize > 0 Then
//        Remove = Items(0).Data
//        lSize = lSize - 1
//        Items(0) = Items(lSize)
//        RebuildHeap 0
//        ReDim Preserve Items(lSize)
//    Else
//        Remove = Empty ' Heap empty
//    End If
//End Function

int Remove()
{
      int nRet= 0;
      if ( gnSize > 0 ) {
            nRet= garItems[0].nData;
            gnSize= gnSize - 1;
            garItems[0]= garItems[ gnSize ];
            RebuildHeap( 0 );
      }
      else {
            nRet= 0;
      }
      return nRet;
}


//Public Sub Add(ByVal Key As Variant, ByVal Data As Variant)
//    ReDim Preserve Items(lSize) ' Make room for the new item.
//    Items(lSize).Key = Key
//    Items(lSize).Data = Data
//    Dim Place As Long, Parent As Long
//    Place = lSize
//    Parent = (Place - 1) / 2
//    Do While Parent >= 0 And (Items(Place).Key > Items(Parent).Key)
//        ' swap Items(Place) and Items(Parent)
//        Dim Temp As HeapItem
//        Temp = Items(Parent)
//        Items(Parent) = Items(Place)
//        Items(Place) = Temp
//        
//        Place = Parent
//        Parent = (Place - 1) / 2
//    Loop
//    lSize = lSize + 1
//End Sub

void Add( int nKeyVal, int nDataVal )
{
      garItems[ gnSize].nKey=  nKeyVal;
      garItems[ gnSize].nData= nDataVal;

      int nPlaceIdx, nParentIdx;
      nPlaceIdx= gnSize;
      nParentIdx = (nPlaceIdx - 1) / 2;

      while ( (nParentIdx >= 0) && (garItems[ nPlaceIdx].nKey > garItems[nParentIdx].nKey) ) {
            //  swap Items(Place) and Items(Parent)
            HeapItem rTemp= garItems[ nParentIdx ];

            garItems[ nParentIdx ]= garItems[ nPlaceIdx ];
            garItems[ nPlaceIdx ]= rTemp;

            nPlaceIdx= nParentIdx;
            nParentIdx= (nPlaceIdx - 1) / 2;
      }
      gnSize++;
}



void CD24Dlg::OnButton1()
{
      Add(1,1000);
      Add(2,2000);
      Add(3,3000);

      RebuildHeap(0);      
      // TODO: Add your control notification handler code here
      
}

 

by: DanRollinsPosted on 2004-08-29 at 11:39:22ID: 11926650

I cannot vouch for how well that program code works, but I think that it is accurate.  If the VB functions do what you want, then the C++ should do the same thing (I think :-).

IMO C++ is not any more complicated that BASIC for such "logic" tasks as this.  It *is* much more compicated for many things... especially interfacing to COM objects and for interactions with GUI, etc.  But that does not apply here.

The reason that all examples of C++ code appear to be complicated to a VB veteran is probably that most array sorting an manipulation examples you will see use pointers into the data while VB code uses the simpler concepts of array indexes.  C++ code ends up being more efficient, but harder to read and understand for VB programmers because the concept of a pointer is basically non-existant for VB programmers.

-- Dan

 

by: jamesreddyPosted on 2004-08-29 at 13:35:40ID: 11927063

Ok avizit...that got me started.  Looking at the code on that site, I was able to start writing my own C++ equivalent.  Then Dan topped it off for me.  Thanks much for the help.  Hopefully, I won't be needing it again.  I'd like to avoid C++ if at all possible in the future.  Needless to say, I will be helping them find a suitable replacement this week so I can go back to what I do best.

Thanks again!

James

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...