CSC301: Natural style is cautious [7/9] |
// prefix order traversal public void printPre () { if (root != null) printPre (root); StdOut.println (); } private static void printPre (Node n) { StdOut.print (n.val + " "); for (Node child : n.children) { printPre (child); } } |
// level order traversal public void printLevel () { Queue<Node> queue = new Queue<>(); if (root != null) queue.enqueue(root); while (!queue.isEmpty()) { Node n = queue.dequeue(); StdOut.print (n.val + " "); for (Node child : n.children) { queue.enqueue(child); } } StdOut.println (); } |
Since there are a variable number of children, it makes sense to disallow null children.
Only the root can be null.
Cautious stye is natural here, since we do not need to check nullity except at the root.