Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary Tree Height

Tags:

binary-tree

I need a general formula to calculate the minimum height of the binary tree and the maximum height of the binary tree. (not the binary search tree)

like image 790
Syed Mehmood Ali Avatar asked Dec 23 '09 06:12

Syed Mehmood Ali


People also ask

What is height of a tree?

Height of the tree is the number of edges in the tree from the root to the deepest node, Height of the empty tree is 0.

How is height of binary tree log N?

In summary, in a complete binary tree with n nodes: the height is h = log2(n + 1), i.e. h is O(log n) • the number of leaves is lh = (n + 1)/2, i.e. roughly half of the nodes are at the leaves.

How do you find the height of a tree in data structure?

To calculate the height of the tree recursively, we need to find the height of it's left subtree and right subtree recursively and add 1 to them (height between the topmost node and its children).

How do you find the height of a tree node?

Height of a node K (of a Binary Tree) = Number of edges in the longest path connecting K to any leaf node.


2 Answers

If you have N elements, the minimum height of a binary tree will be log2(N)+1.

For a full binary tree, the maximum height will be N/2.

For a non-full binary tree, the maximum height will be N.

like image 162
Peter Alexander Avatar answered Sep 27 '22 23:09

Peter Alexander


N - number of nodes.
H - height of the binary tree.

Complete Binary Tree:
Then, with H height N would lie between:

2^H <= N <= (2^(H+1) - 1)

Thus, solving this inequality; we get :

H <= lg(N)  and  H >= (lg(N+1) - 1)

Hence we finally get:

H = floor( lg(N) ) = ceil( (lg(N+1) - 1) )   //as H is integer

(lg : log base 2)

Binary Tree (not necessarily complete):

Max height = N;  

Min Height = floor( lg(N) ) = ceil( (lg(N+1) - 1) )

We get minimum height when binary tree is complete.

like image 27
DoOrDoNot Avatar answered Sep 27 '22 23:09

DoOrDoNot