A little demo from Klaus Schliep about traversing trees using ape.

library(ape)
set.seed(1)
x = rtree(5,FALSE)
plot(x, show.tip.label=FALSE)
nodelabels(); # shows internal node numbers
tiplabels(); # shows numerical tip values (name collision w/ above?!)

plot of chunk unnamed-chunk-1

x$edge
##      [,1] [,2]
## [1,]    6    1
## [2,]    6    7
## [3,]    7    2
## [4,]    7    3
## [5,]    6    8
## [6,]    8    4
## [7,]    8    5

Now we reorder the edge matrix according to a postorder traversal, however this doesn’t change anything about the tree.

x = reorder(x, "postorder")
x$edge
##      [,1] [,2]
## [1,]    8    4
## [2,]    8    5
## [3,]    7    2
## [4,]    7    3
## [5,]    6    1
## [6,]    6    7
## [7,]    6    8

Here is an example that traverses the tree and collects how many taxa are below each node:

ntips = length(x$tip.label)
m = max(x$edge)
res = integer(m)
res[1:ntips] = 1L
parent = x$edge[,1]
child = x$edge[,2]
for(i in 1:nrow(x$edge)){
  res[parent[i]] = res[parent[i]] + res[child[i]]  
}
res
## [1] 1 1 1 1 1 5 2 2