Tree: Height of a Binary Tree

Tree: Height of a Binary Tree
import java.util.*;
import java.io.*;

class Node {
    Node left;
    Node right;
    int data;
    
    Node(int data) {
        this.data = data;
        left = null;
        right = null;
    }
}

class Solution {

    /*
    class Node 
        int data;
        Node left;
        Node right;
    */
    public static int height(Node root) {
        // Write your code here.
          Queue<Node> q = new LinkedList<Node>();
          Queue<Integer> level = new LinkedList<Integer>();
          q.add(root);
          level.add(0);
          
          int currentLevel = 0;
          while(!q.isEmpty()){
              Node current =q.poll();
              currentLevel = level.poll();
              if(current.left !=null){
                  q.add(current.left);
                  level.add(currentLevel+1);
              }
               if(current.right !=null){
                  q.add(current.right);
                  level.add(currentLevel+1);
              }             
          }
          return currentLevel;
    }

    public static Node insert(Node root, int data) {

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s