Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Total number of nodes in a tree data structure?

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 need to know what percentage of the nodes that will have children.

What is the correct term for this ratio of leaf nodes to non-leaf nodes in N?

What is the formula for working out the total number nodes in the three?

Update Someone mention Branching factor in one of the answer but it then disappeared. I think this was the term I was looking for. So shouldn't a formula take the branching factor into account?

Update I should have said an estimate about a hypothetical datastructure, not the exact figure!

like image 668
tpower Avatar asked Feb 05 '09 09:02

tpower


People also ask

How do you find the number of nodes in a tree?

If binary search tree has height h, minimum number of nodes is h+1 (in case of left skewed and right skewed binary search tree). If binary search tree has height h, maximum number of nodes will be when all levels are completely full. Total number of nodes will be 2^0 + 2^1 + …. 2^h = 2^(h+1)-1.

How many nodes are in the tree?

A full binary tree of a given height h has 2h – 1 nodes.

What is the maximum number of nodes in the tree?

2) Maximum number of nodes in a binary tree of height 'h' is 2h – 1. Here height of a tree is maximum number of nodes on root to leaf path. Height of a tree with single node is considered as 1.


1 Answers

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]
              |
             /|\
            / | \
like image 123
Toon Krijthe Avatar answered Nov 08 '22 19:11

Toon Krijthe