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

Java : This function is to search through a binary tree left and right and retur

ID: 3875981 • Letter: J

Question

Java : This function is to search through a binary tree left and right and return a count of the nodes above depth k. This is what I have so far, but I'm getting a Null pointer exception.

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; }

   }

   public int sizeAboveDepth(int k) {

       return abovehelp(root, k, 0);

   }

  

   public int abovehelp(Node x, int k, int count) {

       int szl = abovehelp(x.left, k, count);

       int szr = abovehelp(x.right, k, count);

       if (x != null && count > k) {

           count ++;

           return 1 + szl + szr;

       }

       count ++;

       return 0 + szl + szr;

   }

Explanation / Answer

class Node

{

int data;

Node left, right;

Node(int item)

{

data = item;

left = right = null;

}

}

class BinaryTree

{

Node root;

void countNodes(Node node, int k,int &c)

{

if (node == null)

return;

if (k == 0)

{

return;

}

else

{

countNodes(node.left, k - 1,c++);

countNodes(node.right, k - 1,c++);

}

}

public static void main(String args[]) {

BinaryTree tree = new BinaryTree();

/* Constructed binary tree is

1

/

2 3

/ /

4 5 8

*/

tree.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);

tree.root.right.left = new Node(8);

int c=0

tree.countNodes(tree.root, 2,c);

System.out.print(c);

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote