1	public class Tnode {
     2	   public Tnode(char c) {
     3	      ch = c; left = null; right = null;
     4	   }
     5	   char ch;
     6	   Tnode left, right;
     7	}

8 public class SearchTree { 9 private void buildTree() { 10 char c; 11 Tnode root = null; 12 while ((c = GetChar.getNextChar()) != '\n') { 13 if (root == null) root = new Tnode(c); 14 else addTree(root, c); 15 } 16 treePrint(root); 17 System.out.println("#"); 18 } 19 20 private void addTree(Tnode p, char c) { 21 for (;;) { 22 if ((p.ch) == c) return; // ignore 23 else if ((p.ch) > c) { // go left 24 if ((p.left) == null) { 25 p.left = new Tnode(c); 26 return; 27 } 28 else p = p.left; 29 } 30 else if ((p.ch) < c) { // go right 31 if ((p.right) == null) { 32 p.right = new Tnode(c); 33 return; 34 } 35 else p = p.right; 36 } 37 } 38 } 39 40 private void treePrint(Tnode p) { 41 if (p == null) System.out.print("()"); 42 else { 43 System.out.print("( " + p.ch + " "); 44 treePrint(p.left); 45 System.out.print(" "); 46 treePrint(p.right); 47 System.out.print(" )"); 48 } 49 } 50 51 public static void main(String[] args) { 52 SearchTree searchTree = new SearchTree(); 53 searchTree.buildTree(); 54 } 55 }
56 public class TraverseTree { 57 private char next; 58 59 public void processTree() { 60 scan(); 61 Tnode root = tree(); 62 if (next != '#') error(1); 63 inorderTraversal(root); 64 System.out.println(); 65 } 66 67 private Tnode tree() { 68 Tnode p = null, q, r; 69 if (next == '(') 70 scan(); 71 else error(2); 72 if (next == ')') { 73 scan(); 74 p = null; 75 return p; 76 } 77 if (Character.isLetter(next)) { 78 p = new Tnode(next); 79 scan(); 80 } 81 else error(3); 82 q = tree(); 83 r = tree(); 84 if (next == ')') 85 scan(); 86 else error(4); 87 p.left = q; 88 p.right = r; 89 return p; 90 } 91 92 private void scan() { 93 while (Character.isWhitespace(next = 94 GetChar.getNextChar())) 95 ; 96 } 97 98 private void error(int n) { 99 System.out.println("\n*** ERROR: " + n); 100 System.exit(1); 101 } 102 103 private void inorderTraversal(Tnode p) { 104 if (p != null) { 105 inorderTraversal(p.left); 106 System.out.print(p.ch); 107 inorderTraversal(p.right); 108 } 109 } 110 111 public static void main(String[] args) { 112 TraverseTree traverseTree = 113 new TraverseTree(); 114 traverseTree.processTree(); 115 } 116 }
117 import java.io.*; 118 public class GetChar { 119 private static Reader in = 120 new InputStreamReader(System.in); 121 122 public static char getNextChar() { 123 char ch = ' '; // = ' ' to keep compiler happy 124 try { 125 ch = (char)in.read(); 126 } catch (IOException e) { 127 System.out.println("Exception reading character"); 128 } 129 return ch; 130 } 131 }