Created
March 25, 2015 12:30
-
-
Save kedarmhaswade/9656d7875f90e1702ab5 to your computer and use it in GitHub Desktop.
Java does not have goto
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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