// The Binary Tree ADT -- linked list implementation class BTNode { char data; BTNode leftChild; BTNode rightChild; public BTNode () { } public BTNode (char newData) { data = newData; } public BTNode (char newData, BTNode newLeftChild, BTNode newRightChild) { data = newData; leftChild = newLeftChild; rightChild = newRightChild; } public void setData (char newData) { data = newData; } public void setLeftChild (BTNode newLeftChild) { leftChild = newLeftChild; } public void setRightChild (BTNode newRightChild) { rightChild = newRightChild; } public char getData () { return data; } public BTNode getLeftChild () { return leftChild; } public BTNode getRightChild () { return rightChild; } public void displayBTNode () { System.out.print (data + " "); } } class BTLRADT { BTNode root; public BTLRADT () { } public BTNode getRoot () { return root; } /* it is assumed that the tree is based on the ordering relationship between data in the nodes */ public void insert (char newData) { BTNode newNode = new BTNode (); newNode.data = newData; if (root == null) root = newNode; else { BTNode temp = root; BTNode parent; while (true) { parent = temp; if (newData < temp.data) { //go left temp = temp.leftChild; if (temp == null) { parent.leftChild = newNode; return; } } else { // go right temp = temp.rightChild; if (temp == null) { parent.rightChild = newNode; return; } } } } } public void preOrder (BTNode localRoot) { if (localRoot != null) { localRoot.displayBTNode(); preOrder(localRoot.leftChild); preOrder(localRoot.rightChild); } } public void postOrder (BTNode localRoot) { if (localRoot != null) { postOrder(localRoot.leftChild); postOrder(localRoot.rightChild); localRoot.displayBTNode(); } } public void inOrder (BTNode localRoot) { if (localRoot != null) { inOrder(localRoot.leftChild); localRoot.displayBTNode(); inOrder(localRoot.rightChild); } } public void levelOrder (BTNode localRoot) { BTNode[] queue = new BTNode[20]; int front = 0; int rear = -1; while (localRoot != null) { localRoot.displayBTNode(); if (localRoot.leftChild != null) { rear++; queue[rear] = localRoot.leftChild; } if (localRoot.rightChild != null) { rear++; queue[rear] = localRoot.rightChild; } localRoot = queue[front]; front++; } } } class BTLRex1 { public static void main (String[] args) { BTLRADT tree = new BTLRADT(); tree.insert('b'); tree.insert('i'); tree.insert('n'); tree.insert('a'); tree.insert('r'); tree.insert('y'); tree.insert('t'); tree.insert('r'); tree.insert('e'); tree.insert('e'); tree.insert('e'); tree.insert('x'); tree.insert('a'); tree.insert('m'); tree.insert('p'); tree.insert('l'); tree.insert('e'); /* tree.insert('5'); tree.insert('3'); tree.insert('6'); tree.insert('2'); tree.insert('4'); */ tree.preOrder(tree.getRoot()); System.out.println (); tree.postOrder(tree.getRoot()); System.out.println (); tree.inOrder(tree.getRoot()); System.out.println (); tree.levelOrder(tree.getRoot()); System.out.println (); } }