As Alexey Morozov notes, you can indeed get the count of nodes through various standard formulae, depending on whether the tree is rooted or not, whether you want internal nodes only or not etc.
You are also absolutely correct, of course, that these would not apply if the tree might have nodes with outdegree > 2.
In this case, you will indeed have to somehow pretraverse the tree to get the node count.
This is, in fact, what is implicitly done by encoding the bipartitions which, while not done automatically, can be requested:
```
n_nodes = len(tree.encode_bipartitions())
```
though for your purposes, if you are not actually using the bipartitions, you will find it faster to simply build a list from the iterator instead:
```
nodes = list(tree.preorder_node_iter())
n_nodes = len(nodes)
```
The most efficient way (perhaps only marginally faster than the list approach) might be to count nodes as the tree is being built from the source by passing in a node counting function to the tree reading method using the ``finish_node_fn`` argument. This is shown by the ``f3()`` approach below.
```
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import timeit
import dendropy
# target_data_path = "pythonidae.mle.newick"
target_data_path = "Smith_2001_angiosperms.newick"
target_data_schema = "newick"
def f1():
tree = dendropy.Tree.get(
path=target_data_path,
schema=target_data_schema)
print(len(tree.encode_bipartitions()))
def f2():
tree = dendropy.Tree.get(
path=target_data_path,
schema=target_data_schema)
print(len(list(tree.preorder_node_iter())))
def f3():
node_data = {"count": 0}
def count_nodes(x):
node_data["count"] += 1
tree = dendropy.Tree.get(
path=target_data_path,
schema=target_data_schema,
finish_node_fn=count_nodes)
n_nodes = node_data["count"]
print(n_nodes)
def measure(fn, label, timeit_number=1, timeit_repeat=1):
t1 = timeit.repeat(
fn,
repeat=timeit_repeat,
number=timeit_number)
print("'{}': {}".format(label, t1))
measure(f1, "encode_bipartitions")
measure(f2, "list(tree.preorder_node_iter())")
measure(f3, "finish_node_fn()")
```