Total number of nodes in a tree data structure?

后端 未结 6 551
无人共我
无人共我 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:29

    The formula for calculating the amount of nodes in depth L is: (Given that there are N root nodes)

    NL

    To calculate the number of all nodes one needs to do this for every layer:

    for depth in (1..L)
        nodeCount += N ** depth
    

    If there's only 1 root node, subtract 1 from L and add 1 to the total nodes count.

    Be aware that if in one node the amount of leaves is different from the average case this can have a big impact on your number. The further up in the tree the more impact.

         *                *                 *         N ** 1
        ***              ***               ***        N ** 2
    *** *** ***      *** *** ***       *** *** ***    N ** 3
    

    This is community wiki, so feel free to alter my appalling algebra.

提交回复
热议问题