1

I am drawing a tree like given below. The MWE for it is below:

\documentclass[]{article}   
\usepackage{forest}   
\title{}   
\author{}   
\begin{document}   
\date{}   
\begin{forest}   
    [n   
    [n-1   
    [n-2[$\vdots$]][n-2[$\vdots$]]]   
    [n-1   
    [n-2[$\vdots$]][n-2[$\vdots$]]]]   
\end{forest}   
\end{document}  

tree

I wish to write the count of number of nodes at each level of the tree. For example, adjacent to n, I wish to write 1. In the next level, 2 and so on. Since I am using forest package,

[n\hspace{1cm}1]

doesn't seem to help. Any simple ideas on how to do this?

Edit 1:

I found a related question which is not working for me.

1

A simple robust way would be to name one of the nodes in each level and use the y coordinate of that node (making use of the calc tikzlibrary) to get the correct height for each label. Counting the number of nodes can be done progrmatically - in your case the formula is clearly 2^n (use pgfs pow):

\documentclass[]{article}
\usepackage{forest}
\usetikzlibrary{calc} % let
\newcommand\leftsep{3} % How far left of center line of forest labels appear (cm)
\newcounter{levelcount} % Stores current level in tree
\newcommand\countnodes[1]{% Command to add label at height of node #1
    \draw let \p{L} = (#1) in (-\leftsep,\y{L}) node {\pgfmathparse{int(pow(2,\value{levelcount}))}\pgfmathresult};
    \stepcounter{levelcount} % Step counter for next level
}
\begin{document}
\begin{forest}
[n, name=root % Name root
[n-1, name=level1 % Name a node in level 1
[n-2, name=level2 [$\vdots$]][n-2[$\vdots$]]] % Name a node in level 2
[n-1
[n-2[$\vdots$]][n-2[$\vdots$]]]]
{% Node counting - these must be in order
\countnodes{root}
\countnodes{level1}
\countnodes{level2}
}
\end{forest}
\end{document}

Output:

output

  • After the vdots, I would like to write 2 raised to k, for the k-th level of nodes. I assume this cannot be done using this approach. – GermanShepherd Feb 25 at 10:48
  • Sure, just name your vdots node e.g. mydots and add a command like \draw let \p{L} = (mydots) in (-\leftsep,\y{L}) node {$2^k$}; in the same group ({..}) as the \countnodes commands. (If you want it below the vdots, use e.g. \y{L}-1 instead of \y{L}.) – Pippip19 Feb 25 at 10:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.