Height of a Binary Tree - The Coding Shala

Home >> Interview Questions >> Height of a binary tree

Height of a Binary Tree

The Binary tree is given you have to find the height of the given binary tree. The height of a binary tree h the number of edges between the tree's root and its furthest leaf. (Maximum depth of a Binary Tree.)

Example
Height of a Binary Tree - The Coding Shala

Height of a Binary Tree Java Program


Method 1:

Using recursion.

Java Code: 
public static int height(Node root) {
       // Write your code here.
          int hi = -1;
          if(root == null) return hi;
          return 1+ Math.max(height(root.left), height(root.right));
    }

Method 2:
Using the queue(level order traversal).

Java Code: 

public static int height(Node root) {
       // Write your code here.
          int hi = 0;
          if(root == null) return hi;
          Queue<Node> queue = new LinkedList<>();
          queue.offer(root);
          while(!queue.isEmpty()){
              int size = queue.size();
              for(int i=0; i<size; i++){
                  Node curr = queue.poll();
                  if(curr.left != null) queue.offer(curr.left);
                  if(curr.right != null) queue.offer(curr.right);
              }
              hi++;
          }
        return hi-1;
    }




Other Posts You May Like
Prev<< Find the number of Islands                                    NEXT >>Find Minimum Depth of a Binary Tree
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

New Year Chaos Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala