I have a question about the following code
private void printTree(Node node){
if(node==null) return;
printTree(node.left);
System.out.print(node.data+" ");
printTree(node.right);
}
I don’t really get the point of ‘return;’ statement there. It looks like if node is null, code returns nothing. but then without that line, a compiler generates an exception error.
This is a recursive function (one that calls itself repeatedly). The purpose of the
returnis to ensure that it doesn’t attempt to do so forever, resulting in a null pointer exception as you run off the bottom of the tree.What will happen is that the first time you call this function with a node (usually, but not always, the root node), it will first print out the left sub-tree of that node, then the value of the node itself, then the right sub-tree of that node.
The way it prints out the sub-trees is by calling itself with the top level node of that sub-tree. This is a very common method of elegantly processing recursive structures.
The test for
nullis so that it has a condition where the search down through the levels of the tree stops when it reaches a node that has no children on the particular side you’re examining (left or right).By way of example, let’s say you have the following tree (uppercase letters with their numbers are real nodes with the numbers being their value, and
===markers are nulls):Here’s what will happen, when you call the function with
A.The upshot is that it’s printed out the sequence
DBACEwhich, in a sorted tree, is the elements in sorted order(11, 14, 26, 84, 99).Or a simpler version if you can’t be bothered to read through my voluminous explanation above:
In that case, you’d get
BAor(14,26).