Skip to content

Instantly share code, notes, and snippets.

@kedarmhaswade
Created March 25, 2015 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kedarmhaswade/9656d7875f90e1702ab5 to your computer and use it in GitHub Desktop.
Save kedarmhaswade/9656d7875f90e1702ab5 to your computer and use it in GitHub Desktop.
Java does not have goto
/**
* This is from Donald Knuth's famous paper: Structured Programming with Goto.
* You are printing a binary tree using the Goto statement. The traversal is inorder.
*/
class TreePrintGoto {
private final static class Node {
Node left, right;
final int key;
Node(int key) {
this.key = key;
}
static Node makeTree() {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.right = new Node(5);
return root;
}
}
static void printTree(Node r) {
l1: if (r != null) {
printTree(r.left);
System.out.print(r.key + " ");
r = r.right;
continue l1;
}
}
static void printTreeR(Node r) {
if (r != null) {
printTreeR(r.left);
System.out.print(r.key + " ");
printTreeR(r.right);
}
}
public static void main(String[] args) {
Node root = Node.makeTree();
printTreeR(root);
System.out.println();
printTree(root);
System.out.println();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment