Search code examples
binary-treemaxmindepthformulas

Balanced Binary Trees Depth


When given a number of nodes we are able to calculate the min depth of the binary tree by doing log2(n)

Where n is the number of nodes.

If you draw the tree out for the maximum depth for example 12 nodes you work out that the maximum depth can only be 4 if the tree is to remained balanced.

                0
               /   \
              0     0
            /  \   / \
           0    0 0   0
          /\     \     \ 
        0   0      0    0

Sorry for the bad ascii art. Does anyone know of a forumla that is able to calculate the max depth of a binary tree when given the number of nodes? Or at least point me in the right direction?


Solution

  • By using the root element :

    int maxHeight(BinaryTree *p) {
      if (!p) return 0;
      int left_height = maxHeight(p->left);
      int right_height = maxHeight(p->right);
      return (left_height > right_height) ? left_height + 1 : right_height + 1;
    }
    

    By using the number of nodes and some math logic (which I definitely cannot express properly (I'm by no means a math guru); but here it is) :

    Observation :

    • 2-3 nodes => maxDepth = 1 (2 = 2^1, 3 = 2^1,.. < 2^2 )
    • 4-7 nodes => maxDepth = 2 (4 = 2^2, 5 = 2^2,.., 6 = 2^2,.., 7 = 2^2,... < 2^3)
    • 8-15 nodes => maxDepth = 3
    • ...

    Analysis :

    • m => max Depth (actual the INT part of the depth, discard any decimal places)
    • n => number of nodes

    • ln => natural logarithm (=log[e])

    • 2^m = n

    • ln(2^m) = ln(n)

    • m*ln(2) = ln(n)
    • m = ln(n)/ln(2)

    Conclusion :

    Now, if m = 2,... , then the maximum depth is 2. Just get the int part of it. ;-)


    NOTE: I'm definitely re-inventing the wheel here; but that's probably part of the fun of dealing with something you know nothing about; and doing it, solely following your instinct and observations... :-)