w3resource

Java Exercises: Find the maximum depth of a given a binary tree

Java Basic: Exercise-130 with Solution

Write a Java program to find the maximum depth of a given a binary tree.
Sample Output: The Maximum depth of the binary tree is: 3

Sample Solution:

Java Code:

class Node
{
    int data;
    Node left, right;
    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}
public class BinaryTree
{
    //Root of the Binary Tree
    Node root;
 
   public int maxDepth(Node root) {
    if(root==null)
        return 0;
    int left_Depth = maxDepth(root.left);
    int right_Depth = maxDepth(root.right);
    int bigger = Math.max(left_Depth, right_Depth);
    return bigger+1;
}
     /* Driver program to test above functions */
    public static void main(String args[])
    {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(55);
        tree.root.left = new Node(21);
        tree.root.right = new Node(80);
        tree.root.left.left = new Node(9);
        tree.root.left.right = new Node(29);
        tree.root.right.left = new Node(76);
        tree.root.right.right = new Node(91);
        System.out.println("The Maximum depth of the binary tree is: " + tree.maxDepth(tree.root));
    }
}

Sample Output:

The Maximum depth of the binary tree is: 3  

Flowchart:

Flowchart: Java exercises: Calculate the median of unsorted array of integers, find the median of it.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Find the new length of a given sorted array where each element appear only once.
Next: Write a Java program to find the new length of a given sorted array where each element appear only once.

What is the difficulty level of this exercise?



Java: Tips of the Day

Execution of console commands:

Java allows you to execute console commands directly from code using a class Runtime. It is very important not to forget about exception handling.

For example, let's try to open a PDF file through a Java terminal:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
  
public class ShellCommandExec {
  
  public static void main(String[] args) {
    String gnomeOpenCommand = "gnome-open //home//user//Documents//MyDoc.pdf";
  
    try {
      Runtime rt = Runtime.getRuntime();
      Process processObj = rt.exec(gnomeOpenCommand);
  
      InputStream stdin = processObj.getErrorStream();
      InputStreamReader isr = new InputStreamReader(stdin);
      BufferedReader br = new BufferedReader(isr);
  
      String myoutput = "";
  
      while ((myoutput=br.readLine()) != null) {
        myoutput = myoutput+"\n";
      }
      System.out.println(myoutput);
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}