Find the Height of a Binary Tree –

Blog

Height of a binary tree

Height of a binary tree is the maximum depth of the tree. As you can see in the above diagram the height of it is 4 because it contains 4 levels of depth.

To find out the depth of the tree we will create an algorithm which will perform the following operations.

  • We will recursively find out the depth of the left sub tree and right sub tree.
  • Then get the max of both sides depth and return it.

Time complexity: O(n). Space complexity: O(n).

Video

Warnings

  • These methods do not work well if the tree is on sloping ground. A professional surveyor uses electronic transits in these situations, but these are typically too expensive for home use.

    Thanks! Helpful 2 Not Helpful 1

  • While the angle of elevation methods, if used correctly, can calculate the correct height within 2-3 feet, there is abundant opportunity for human error, especially if the tree is angled or on a slope. If precision is absolutely necessary, consult your local extension service or other such agency for assistance.

    Thanks! Helpful Not Helpful 1

Advertisement

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Finding The Height With Recursion (Depth First search approach)

Let us consider an example to understand the approach in an easier way. Consider the following Binary Tree, with ‘a’ as the root node and ‘h’, ‘e’, ‘f’ and ‘g’ as the leaf node: 

How do you find the diameter?

where:

  • left_height + right_height + 1 is the diameter through the binary tree’s root.
  • max(left_diameter, right_diameter) is the max of each side’s diameter, i.e. when the longest path does not pass through the binary tree’s root.

Algorithm to find the height of a binary tree

Now that we have found a way to find the height of the binary tree, we will formulate the algorithm for finding the height as follows.

  1. If we find an empty root node, we will say that the height of the tree is 0.
  2. Otherwise, we will find the height of the left subtree and right subtree recursively.
  3. After finding the height of the left subtree and right subtree, we will calculate their maximum height.
  4. We will add 1 to the maximum height. That will be the height of the binary tree.

Algorithm

Let’s conceptualize an algorithm to find the diameter of a given binary search tree.

Let’s start with a basic Node and Tree class structures.

Step 1: Design the Height Method

The first step is to design the method that computes the height of tree, subtree, or node. The height is equal to number of nodes from the root to leaf on the longest path from the root.

For example, the longest path in this tree is from the root to the furthest leaf. Its height is 3.

Here’s another example. There are 7 nodes on the longest path from the root to the furthest leaf. Its height is 7.

Another way to look at height is to traverse the tree and find all of the paths from root to leaf. The one with the most nodes is the height of the tree.

Using recursion, we can design the height like this:

Step 2: Design the Diameter Method

Recall how we compute the diameter:

What do you notice?

  1. Get the left child’s height.
  2. Get the right child’s height.
  3. Get the left child’s diameter. <- we can do this recursively
  4. Get the right child’s diameter. <- we can do this recursively
  5. Then plug the values into the above formula.

Applications of Binary Tree:

  1. Its used in many search applications and algorithms which constantly display and store data. For instance, map including set objects in many libraries.
  2. Its utilized in 3D video game to conclude which objects need to be executed.
  3. Its used in nearly every high-bandwidth router to store router tables.
  4. Its used in construction of compilers and (implicit) calculators to parse declarations.

Java

// An iterative java program to find height of binary tree import java.util.LinkedList;import java.util.Queue; // A binary tree nodeclass Node{int data;Node left, right; Node(int item){data = item;left = right;}} class BinaryTree{Node root; // Iterative method to find height of Binary Treeint treeHeight(Node node){// Base Caseif (node == null)return ; // Create an empty queue for level order traversalQueue<Node> q = new LinkedList(); // Enqueue Root and initialize heightq.add(node);int height = ; while (1 == 1){// nodeCount (queue size) indicates number of nodes// at current level.int nodeCount = q.size();if (nodeCount == )return height;height++; // Dequeue all nodes of current level and Enqueue all// nodes of next levelwhile (nodeCount > ){Node newnode = q.peek();q.remove();if (newnode.left != null)q.add(newnode.left);if (newnode.right != null)q.add(newnode.right);nodeCount–;}}} // Driver program to test above functionspublic static void main(String args[]){BinaryTree tree = new BinaryTree(); // Let us create a binary tree shown in above diagramtree.root = new Node(1);tree.root.left = new Node(2);tree.root.right = new Node(3);tree.root.left.left = new Node(4);tree.root.left.right = new Node(5);System.out.println(“Height of tree is ” + tree.treeHeight(tree.root));}} // This code has been contributed by Mayank Jaiswal

C#

// An iterative C# program to// find height of binary treeusing System;using System.Collections.Generic;// A binary tree nodeclass Node{public int data;public Node left, right;public Node(int item){data = item;left = right;}}public class BinaryTree{Node root;// Iterative method to find// height of Binary Treeint treeHeight(Node node){// Base Caseif (node == null)return 0;// Create an empty queue// for level order traversalQueue<Node> q = new Queue<Node>();// Enqueue Root and initialize heightq.Enqueue(node);int height = 0;while (1 == 1){// nodeCount (queue size) indicates// number of nodes at current level.int nodeCount = q.Count;if (nodeCount == 0)return height;height++;// Dequeue all nodes of current// level and Enqueue all// nodes of next levelwhile (nodeCount > 0){Node newnode = q.Peek();queue();if (newnode.left != null)q.Enqueue(newnode.left);if (newnode.right != null)q.Enqueue(newnode.right);nodeCount–;}}}// Driver codepublic static void Main(String []args){BinaryTree tree = new BinaryTree(); // Let us create a binary// tree shown in above diagramtree.root = new Node(1);tree.root.left = new Node(2);tree.root.right = new Node(3);tree.root.left.left = new Node(4);tree.root.left.right = new Node(5);Console.WriteLine(“Height of tree is ” +tree.treeHeight(tree.root));}}// This code has been contributed by 29AjayKumar

Pseudocode

Following is the pseudocode of the algorithm:

Find binary tree height recursively

The simplest way to resolve the problem of finding the height of a binary tree, and probably the first thing that comes to the mind is to use recursion.

We know that every node has two children, so at the root the height will be 1 plus the maximum height between the right and left sub-trees. A node that has no children has a height of 0.

With that information we can concoct an algorithm like the following one:

And we are done!

Complexity

Time complexity : O(n)

It is linear as we are traversing the all nodes of the binary tree recursively and maintaining the height. So, the time complexity is O(N) where N is the number of nodes in the tree.

This can be solved using Breadth First Search as well.

Tags