Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating the height of a binary tree

I need help with the theory on calculating the height of a binary tree, typically the notation.

I have read the following article:

Calculating height of a binary tree

And one of the posts gives the following notation:

height(node) = max(height(node.L), height(node.R)) + 1

Let's assume I have the following binary tree:

     10
   /   \  
  5    30
 / \   /  \ 
4  8  28  42

Do I therefore calculate the max value on the left node (8) and the max node on the right (42) and then add 1? I don't quite understand how this notation works in order to calculate the height of the tree.

like image 605
Phorce Avatar asked May 21 '13 18:05

Phorce


People also ask

How do you find the height of a binary tree?

Calculating minimum and maximum height from the number of nodes: If there are n nodes in a binary search tree, maximum height of the binary search tree is n-1 and minimum height is ceil(log2(n+1))-1.

How do you estimate the height of a tree?

Calculating tree height requires the use of basic trigonometry: h = Tan A x d, where h is the tree height, d is the distance from tree, and A is the angle to the top of the tree. Since your measurements will be made at eye level, you need to know your eye height (height of your eye above the ground).

What is the height of a node in a binary tree?

The height of a node is the number of edges from the node to the deepest leaf. The height of a tree is a height of the root. A full binary tree.is a binary tree in which each node has exactly zero or two children.

What is the recursive formula to find the height of a binary tree?

The height of a binary tree is found using the recursive Depth-First Search (DFS) algorithm, as shown below: Base case: If there is no node, return 0. Else: If there are 1 or 2 children, return the maximum of the height of the left and right sub-trees, plus 1 to account for the current node.


1 Answers

I'll try to explain how this recursive algorithm works:

height(10) = max(height(5), height(30)) + 1

height(30) = max(height(28), height(42)) + 1
height(42) = 0 (no children)
height(28) = 0 (no children)

height(5) =  max(height(4), height(8)) + 1
height(4) = 0 (no children)
height(8) = 0 (no children)

So if you want to calculate height(10), you have to expand the recursion down, and than substitute results backwards.

height(5)  = max(0, 0) + 1
height(30) = max(0, 0) + 1
height(10) = max(1, 1) + 1
height(10) = 2

EDIT:

As noted in comments:
height of binary tree = number of layers - 1
Therefore there should be assumption that height of empty node is equal to -1 i.e:

height(empty) = -1 

or

height(null) = -1 

this way

height(42) = max(height(null), height(null)) + 1
height(42) = max(-1, -1) + 1
height(42) = -1 + 1
height(42) = 0

I have corrected calculation above.

like image 120
Ondrej Bozek Avatar answered Sep 28 '22 05:09

Ondrej Bozek