Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to enumerate all tree items?

Status
Not open for further replies.

tabaar

Programmer
Jun 12, 2001
34
US
How to enumerate _all_ CTreeCtrl items in loop?

Great thanx!
 
Recursion!! I've never done the exact code in VC++ but recursion is generaly the best way to iterate through any tree. Here's some pseudo code:
Code:
visit(root);// call recursive function with the root of the
// tree as your starting point

function visit(Node){
  Iterator children = Node.getChildren();
  // get all the children or branches or whatever you want
  // to call them

  while(it.hasNext(){
    visit(it.next());
  }
  // then process your current node, or process it first
  // depending on what exactly you're doing

}// end visit function

Hope this helped. Good luck. MYenigmaSELF:-9
myenigmaself@yahoo.com
 
Thank you, but I'd like to see _real implementation_ of this. I have some code, but it enumerates only items of the _first_ root item of my tree:

CTreeCtrl& ctl;
HTREEITEM hItem = ctl.GetRootItem();
HTREEITEM hItemTmp = hItem;
a1: hItem = hItemTmp;
while(hItem != NULL){
// Do something with hItem here...
hItemTmp = ctl.GetChildItem(hItem);
if (hItemTmp) goto a1;
hItem = ctl.GetNextSiblingItem(hItem);
}

So, my question is: how to enum. _all_ tree items?

Great thanx!
 
Well, I would like to state up front I have not used a CTreeCtrl object before but this is based on assumption of prior knowledge of trees.

This will use recursion and work bottom up

Code:
void traverse(CTreeCtrl* pCtrl, HTREEITEM hItem)
{
    
    if(!hItem)return; // handle null

    traverse(pCtrl->GetNextSiblingItem(hItem));
    traverse(pCtrl->GetChildItem(hItem);

    // do stuff with hItem
}[code]

I think it would look something like this.

Matt
 
Yuck. Spaghetti code. Just a side note, it's bad programming practice to use goto statements and labels and such. I must reiterate, yuck! As for real code:
Code:
CTreeCtrl& ctl;
//fill your tree
HTREEITEM hItem = ctl.GetRootItem();
traverse(hItem);

//then use this function
void traverse(HTREEITEM &hItem){
  //process your hItem here
  HTREEITEM hItemTmp=GetChildItem(hItem);
  while(hItemTmp!=NULL)
    traverse(hItemTmp);
    hItemTmp=GetNextSiblingItem(hItemTmp);
  }
}
there, try that. I've never done it this way, CTreeCtrl isn't how I would have implemented it, but this should work. Good Luek MYenigmaSELF:-9
myenigmaself@yahoo.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top