I have successfully written a method to print the values of all the nodes in the subtree rooted at a given node (code pasted below under the label "Working Code"). However, this printTree method is in the Main class (as opposed to being in the Node class itself). I am wondering if it is possible (and ideal?) to rewrite the code so that the printTree method is in the Node class itself? My attempt is below (code pasted below under the label "Non Working Code"), but it threw a Null Pointer Exception. Thank you!
WORKING CODE:
public class Node {
int value;
Node left;
Node right;
public Node(int value, Node left, Node right)
{
this.value = value;
this.left = left;
this.right = right;
}
}
public class Main {
public static void printTree(Node current)
{
if (current != null)
{
System.out.println(current.value);
printTree(current.left);
printTree(current.right);
}
return;
}
public static void main(String[] args) {
// write your code here
Node a = new Node(3, new Node(4, null, null), new Node(5, null, null));
printTree(a);
}
}
NON WORKING CODE (in Node class):
public void printTree()
{
Node current = this;
if (current != null)
{
System.out.println(current.value);
current.left.printTree();
current.right.printTree();
}
return;
}
The problem is not in the
Node current = this;
line. But in thelines.
Because even when current is not null, current.left or current.right could be null. And you are trying to invoke
printTree()
on a null object.Fix: