Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA : Recursively complete the IsPerfectlyBalancedH method using one helper fun

ID: 3877474 • Letter: J

Question

JAVA : Recursively complete the IsPerfectlyBalancedH method using one helper function for a binary tree.

  

public class MyIntSET {

   private Node root;

   private static class Node {

       public final int key;

       public Node left, right;

       public Node(int key) { this.key = key; }

   }

  

   // tree is perfect if for every node, height of left == height of right children

   // hint: in the helper, return -2 if the tree is not perfect, otherwise return the height

   public boolean isPerfectlyBalancedH() {

return 0;}

Explanation / Answer

public int Depth(Node root)

{

   int depth = 0;

   while (root != null)

   {

      depth++;

      node = node.left;

   }

   return depth;

}

public boolean isPerfect(Node root, int depth, int level)

{

    if (root == null)

        return true;

    if (root.left == null && root.right== null)

        return (d == level+1);

    if (root.left == null || root.right == null)

        return false;

    return isPerfect(root.left, depth, level+1) && isPerfect(root.right, depth, level+1);

}


public boolean isPerfectlyBalancedH() {

int depth = Depth(root);

   return isPerfect(root, depth, 0);

}