MATLAB: How to get the “depth” of a tree


I'm looking for the node that is the farthest from the "top" of the tree and in particular: how far the distance to the farthest node is? (I continue using the tree in another place, where there is a restriction on how many levels the tree can have, rather than on how many splits there are – which, as I understand it, is what You can limit when building the tree)
In the tree below, the distance would be 7, which is the number of steps between the topmost point on the one hand and either one of the -1 and 1 lowest in the picture.
Does any one know an elegant solution? The tree-object has a lot of information, but I can't figure out how to use it for this objective.
bw, Staffan

Best Answer

  • This should work:
    function depth = treedepth(tree)
    parent = tree.Parent;
    depth = 0;
    node = parent(end);
    while node~=0
    depth = depth + 1;
    node = parent(node);