Total number of nodes in a tree data structure?

后端 未结 6 614
无人共我
无人共我 2021-01-31 05:38

I have a tree data structure that is L levels deep each node has about N nodes. I want to work-out the total number of nodes in the tree. To do this (I think) I

6条回答
  •  青春惊慌失措
    2021-01-31 06:18

    Ok, each node has about N subnodes and the tree is L levels deep.

    With 1 level, the tree has 1 node.
    With 2 levels, the tree has 1 + N nodes.
    With 3 levels, the tree has 1 + N + N^2 nodes.
    With L levels, the tree has 1 + N + N^2 + ... + N^(L-1) nodes.
    

    The total number of nodes is (N^L-1) / (N-1).

    Ok, just a small example why, it is exponential:

                        [NODE]
                          |
                         /|\
                        / | \
                       /  |  \
                      /   |   \
                [NODE]  [NODE] [NODE]
                  |
                 /|\
                / | \
    

提交回复
热议问题