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);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.