Sorting a tree

Is there a simple way (i.e. a currently implemented method) to sort a tree along one of its branches/leafs?


You can take a look at TTree::BuildIndex and TTree::GetTreeIndex (and TVirtualTreeIndex).


Philippe, thanks again.

I think you meant TTreeIndex. I must say the documentation on that class is extremely cryptic…it took me
and another person about 10 minutes of guessing to figure out how to loop through subsequent index entries.

To clarify – it’s very clear from the documentation how to build and index and find a tree entry for a give leaf value…but in our case we needed to just loop through the (sorted) index entries. We eventually found out that this can be done using ptree->GetTreeIndex()->GetIndex() – which is not documented at all.

I am unfortunately having trouble getting a meaningful result out of my attempts to sort a tree. When I use the technique described above on relatively small files (<50 entries), everything works great. However for somewhat larger files the sorting is clearly wrong. I am attaching two such example files.

The actual sorting procedure is the following (also attached):

  std::cout<< "Entries:" <<  ptree->GetEntries()<< std::endl;
  TTreeIndex *I=(TTreeIndex*)ptree->GetTreeIndex(); // get the tree index
  Long64_t* index=I->GetIndex(); //create an array of entries in sorted order

  TLeaf* time=ptree->GetBranch("event")->GetLeaf("time");
  for (int i=0;i<ptree->GetEntries();i++){
    std::cout <<time->GetValue() << std::endl; //print the (hopefully sorted) time

Just load the files into root, and run test.C. For good_file.root things come out perfectly sorted, for problem_file.root it’s clearly is not. Any clue as to what I am doing wrong?
problem_file.root (76 KB)
good_file.root (13.5 KB)
test.C (468 Bytes)


The value in time, overflow the calculated index value when using as a major value // fIndexValues[i] = major<<31 + minorYou can solve the problem by using: ptree->BuildIndex("0","time"); .


Yep that worked, thanks a million Philippe!