Chapter 8 of Robert lafore, Java data structures and algorithms
/* Programming job 8.1 from tree. java program (list 8.1), modify it to create a binary tree (such as A, B, and so on) with the character string entered by the user, each letter is displayed in the respective node. Create a tree so that each node containing letters is a leaf node. The parent node can have non-letter signs, such as '+ '. Make sure that each parent node has exactly two subnodes. Do not worry about tree imbalance. Note that this is not a search tree; there is no quick way to find nodes. The final result can be as shown below: ++ e + d -- + c -- a B -- One method is to create an array of trees.. (A group of unconnected trees is called forests .) Each letter entered by the user is used as a node. When each node is used as a tree, the node is the root. Now put these single-node trees in the array. Next we will create a tree with '+' as the root and two single-node trees as its subnodes. Add the single-node tree in the array to the Tree of the big point in sequence. Do not worry if it is a Balance Tree. Actually, you can overwrite the array unit with the generated middle tree. The content of the array unit has been added to the tree. The find (), insert (), and delete () routines are only used in the search tree and can be deleted. The displaytree () and traversal methods are retained, which are common to all Binary Trees. 8.2 extend the functions in programming job 8.1 to create a balance tree. One way is to ensure that the node is available at the bottom layer. Start to build each pair of Single-node trees into a three-node tree, with '+' as the root. In this way, there is a three-node forest. Merge each pair of Three-node trees into a forest of seven-node trees. As the number of nodes per tree increases, the number of trees decreases until there is only one tree at the end. 8.3 still starts with the tree. Java program. Create a tree based on the characters entered by the user. This time, create a full tree-except that the rightmost of the bottom layer may be empty, the other Layer Nodes are completely full trees. It seems that a character pyramid is created. (This sorting method does not match the three traversal methods discussed earlier in this chapter .) Therefore, the abcdefghij string is arranged as follows: a B c d e f g h I j -- one way to create this tree is from top to bottom, instead of starting from the bottom up like the first two questions in a programming job. Start from creating a node that serves as the root of the last tree. If the node number is the same as the alphabetic order, and 1 is the root node, the number of the Left subnode of the node numbered N is 2 * n + 1. You can use a recursive method to create two nodes and call them in each subnode. The node creation sequence does not need to be the same as the sequence in which they are inserted into the tree. As with the previous question in a programming job, you can delete some methods of the Search Tree in the tree class. 8.4 compile a program to create a tree based on the suffix expression, as shown in Figure 8.11 in this chapter. You need to modify the tree class in the tree. Java program (Listing 8.1) and the parsepost class in the single Postfix. Java program (listing 4th. For more details, see solution in Figure 8.11. After the tree is created, the prefix, infix, and suffix expression corresponding to the arithmetic expression can be obtained through traversing the tree. Infix expressions require parentheses to avoid ambiguous expressions. In the inorder () method, left brackets are added before the first recursive call, and right brackets are added after the second recursive call. 8.5 write a program to implement the coding and decoding of the user. Do the following: accept a text message, possibly of more than one line. create a Huffman tree for this message. create a code table. encode the message into binary. decode the message from binary back to text. if the information is very short, the program can display the created user tree. Programming job 8.1, 8.2, and 8.3 methods will be helpful. You can use the string variable to store binary numbers as sequences of characters 1 and 0. Unless necessary, actual bitwise processing is not required. */Package chap08; // tree. java // demonstrates Binary Tree // to run this program: C> JAVA treeappimport Java. io. *; import Java. util. *; // for Stack class /////////////////////////////////// /// // class node {public char cchar; public node leftchild; // This node's left childpublic node rightchild; // This node's right childpublic node () {} public node (char c) {cchar = C ;} public void Displaynode () // display ourself {system. out. print ('{'); system. out. print (cchar); system. out. print ("}");}} // end class node /////////////////////////////////// ///// // class tree implements comparable {// changed to publicpublic Node root; // first node of treepublic int weight; // weight // ----------------------------------------------------------------- public tree () // constructor {root = NUL L;} // No nodes in tree yet // added the tostring () method Public String tostring () {return root. cchar + "";} // ------------------------------------------------------------- public void traverse (INT traversetype) {Switch (traversetype) {Case 1: system. out. print ("\ npreorder traversal:"); preorder (Root); break; Case 2: system. out. print ("\ ninorder traversal:"); inorder (Root); break; Case 3: system. out. print ("\ npostorder t Raversal: "); postorder (Root); break;} system. Out. println ();} // reset private void preorder (node localroot) {If (localroot! = NULL) {system. out. print (localroot. cchar + ""); preorder (localroot. leftchild); preorder (localroot. rightchild) ;}}// --------------------------------------------------------------- private void inorder (node localroot) {If (localroot! = NULL) {system. out. print ("("); inorder (localroot. leftchild); system. out. print (localroot. cchar + ""); inorder (localroot. rightchild); system. out. print (")") ;}}// --------------------------------------------------------------- private void postorder (node localroot) {If (localroot! = NULL) {postorder (localroot. leftchild); postorder (localroot. rightchild); system. out. print (localroot. cchar + "") ;}/// --------------------------------------------------------------- public void displaytree () {stack globalstack = new stack (); globalstack. push (Root); int nblks = 32; Boolean isrowempty = false; system. out. println ("..................................... ................. "); While (isrowempty = False) {stack localstack = new stack (); isrowempty = true; For (Int J = 0; j <nblanks; j ++) system. out. print (''); While (globalstack. isempty () = false) {node temp = (node) globalstack. pop (); If (temp! = NULL) {system. Out. Print (temp. cchar); localstack. Push (temp. leftchild); localstack. Push (temp. rightchild); If (temp. leftchild! = NULL | temp. rightchild! = NULL) isrowempty = false;} else {system. out. print ("--"); localstack. push (null); localstack. push (null) ;}for (Int J = 0; j <nblanks * 2-2; j ++) system. out. print ('');} // end while globalstack not emptysystem. out. println (); nblks/= 2; while (localstack. isempty () = false) globalstack. push (localstack. pop ();} // end while isrowempty is falsesystem. out. println ("..................................... ................. ");} // end displaytree () // ----------------------------------------------------------------- @ overridepublic int compareto (Object O) {If (O = NULL) {return-1 ;} return weight-(tree) O ). weight ;}} // end class tree /////////////////////////////////// /// // public class treeapp {// programming job 8.1 public static void code8_1 () throws ioexception {system. out. println ("Enter at least two characters):"); string STR = getstring (); tree [] array = new tree [Str. length ()]; for (INT I = 0; I <Str. length (); I ++) {// create a single-node tree array tree temp = new tree (); temp. root = new node (Str. charat (I); array [I] = temp;} For (INT I = 1; I <Str. length (); I ++) {tree temp = new tree (); temp. root = new node ('+'); temp. root. leftchild = array [I-1]. root; temp. root. rightchild = array [I]. root; array [I] = temp;} tree lasttree = array [Str. length ()-1]; lasttree. displaytree ();} // programming job 8.2 // This is the balanced binary tree public static void code8_2 () throws ioexception {system. out. println ("Enter at least two characters):"); string STR = getstring (); tree [] array = new tree [Str. length ()]; for (INT I = 0; I <array. length; I ++) {// create a single-node tree array tree temp = new tree (); temp. root = new node (Str. charat (I); array [I] = temp;} tree [] temparray; while (array. length> 1) {temparray = new tree [(array. length-1)/2 + 1]; Int J =-1; int I = 0; For (; I + 1 <array. length; I + = 2) {tree temp = new tree (); temp. root = new node ('+'); temp. root. leftchild = array [I]. root; temp. root. rightchild = array [I + 1]. root; temparray [++ J] = temp;} if (I <array. length) {tree temp = new tree (); temp. root = new node ('+'); temp. root. leftchild = array [array. length-1]. root; temparray [++ J] = temp; // temparray [++ J] = array [I];} array = temparray;} tree lasttree = array [array. length-1]; lasttree. displaytree ();} // programming job 8.2 // This is the real balance Binary Tree public static void code8_2_1 () throws ioexception {system. out. println ("Enter at least two characters):"); string STR = getstring (); tree [] array = new tree [Str. length ()]; for (INT I = 0; I <array. length; I ++) {// create a single-node tree array tree temp = new tree (); temp. root = new node (Str. charat (I); array [I] = temp;} tree lasttree = connecttree (array, 0, array. length-1); lasttree. displaytree ();} Private Static tree connecttree (tree [] array, int left, int right) {If (Left = right) {return array [left];} else {tree temptree = new tree (); temptree. root = new node ('+'); temptree. root. leftchild = connecttree (array, left, (right + Left)/2 ). root; temptree. root. rightchild = connecttree (array, (right + Left)/2 + 1, right ). root; return temptree ;}// programming job 8.3 public static void code8_3 () throws ioexception {system. out. println ("Enter at least two characters):"); string STR = getstring (); tree [] array = new tree [Str. length ()]; for (INT I = 0; I <array. length; I ++) {// create a single-node tree array tree temp = new tree (); temp. root = new node (Str. charat (I); array [I] = temp;} tree lasttree = connecttree1 (array, 0); lasttree. displaytree ();} Private Static tree connecttree1 (tree [] array, int index) {If (Index * 2 + 1> array. length-1) {// No subtree return array [Index];} else if (Index * 2 + 2> array. length-1) {// left subtree tree temp = array [Index]; temp. root. leftchild = connecttree1 (array, Index * 2 + 1 ). root; return temp;} else {// left/right subtree tree temp = array [Index]; temp. root. leftchild = connecttree1 (array, Index * 2 + 1 ). root; temp. root. rightchild = connecttree1 (array, Index * 2 + 2 ). root; return temp;} public static void main (string [] ARGs) throws ioexception {// programming job 8.1-8.3 // code8_1 (); // code8_2 (); // code8_2_1 (); code8_3 () ;}// end main () // define public static string getstring () throws ioexception {inputstreamreader ISR = new inputstreamreader (system. in); bufferedreader BR = new bufferedreader (ISR); string S = BR. readline (); Return s;} // ------------------------------------------------------------- public static char getchar () throws ioexception {string S = getstring (); Return S. charat (0);} // ------------------------------------------------------------- public static int getint () throws ioexception {string S = getstring (); Return integer. parseint (s );} // -----------------------------------------------------------} // end class treeapp /////////////////////////////// /////////////////////////////////
Package chap08; // Postfix. java // parses Postfix arithmetic expressions // to run this program: C> JAVA postfixappimport Java. io. *; // For I/o ////////////////////////////////// /// // class stackx {private int maxsize; private tree [] stackarray; private int top; // using public stackx (INT size) // constructor {maxsize = size; stackarray = new tree [maxsize]; top =-1;} // -------------------------------------------------------------- public void push (tree J) // put item on top of stack {stackarray [++ top] = J ;} // retrieve public tree POP () // take item from top of stack {return stackarray [top --];} // ---------------------------------------------------------------- public tree PEEK () // peek at top of stack {return stackarray [Top];} // ------------------------------------------------------------------ public Boolean isempty () // true if Stack is empty {return (Top =-1);} // ------------------------------------------------------------ public Boolean isfull () // true if Stack is full {return (Top = maxsize-1);} // ---------------------------------------------------------- public int size () // return size {return top + 1 ;} // -------------------------------------------------------------- public tree peekn (int n) // peek at index n {return stackarray [N];} // retrieve public void displaystack (string s) {system. out. print (s); system. out. print ("stack (bottom --> top):"); For (Int J = 0; j <size (); j ++) {system. out. print (peekn (j); system. out. print ('');} system. out. println ("");} // ------------------------------------------------------------} // end class stackx /////////////////////////////// //// // class parsepost {private stackx thestack; private string input; // specify public parsepost (string s) {input = s;} // ---------------------------------------------------------- // program job 8.4 public tree doparse () {thestack = new stackx (20); // make new stackchar ch; Int J; tree num1, num2, interans; For (j = 0; j <input. length (); j ++) // For each char, {CH = input. charat (j); // read from inputthestack. displaystack ("" + CH + ""); // * diagnostic * If (CH> = '0' & Ch <= '9 ') {// if it's a numbertree temp = new tree (); temp. root = new node (CH); thestack. push (temp); // push it} else // It's an operator {num2 = thestack. pop (); // pop operandsnum1 = thestack. pop (); tree temp; Switch (CH) // do arithmetic {Case '+': temp = new tree (); temp. root = new node ('+'); temp. root. leftchild = num1.root; temp. root. rightchild = num2.root; thestack. push (temp); break; Case '-': temp = new tree (); temp. root = new node ('-'); temp. root. leftchild = num1.root; temp. root. rightchild = num2.root; thestack. push (temp); break; Case '*': temp = new tree (); temp. root = new node ('*'); temp. root. leftchild = num1.root; temp. root. rightchild = num2.root; thestack. push (temp); break; Case '/': temp = new tree (); temp. root = new node ('/'); temp. root. leftchild = num1.root; temp. root. rightchild = num2.root; thestack. push (temp); break; default: // interans = 0;} // end switch // thestack. push (interans); // push result} // end else} // end forinterans = thestack. pop (); // get answerreturn interans;} // end doparse ()} // end class parsepost /////////////////////////////////// /// // public class postfixapp {public static void main (string [] ARGs) throws ioexception {string input; tree output; system. out. print ("Enter Postfix:"); system. out. flush (); input = getstring (); // read a string from kbdif (input. equals ("") // quit if [enter] return; // make a parserparsepost aparser = new parsepost (input); Output = aparser. doparse (); // do the evaluation // system. out. println ("evaluates to" + output); output. displaytree (); output. traverse (1); output. traverse (2); output. traverse (3);} // end main () // returns public static string getstring () throws ioexception {inputstreamreader ISR = new inputstreamreader (system. in); bufferedreader BR = new bufferedreader (ISR); string S = BR. readline (); Return s ;} // --------------------------------------------------------------} // end class postfixapp /////////////////////////////// /////////////////////////////////
Package chap08; import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstreamreader; import Java. util. hashmap; import Java. util. iterator; import Java. util. map; import Java. util. priorityqueue; import Java. util. queue; import Java. util. set; import Java. util. treemap; // ================================================ ===================================================/ /programming job 8.5 public class Huffman {public stat Ic Map <character, string> map_char_code; public static Map <string, character> map_code_char; static {map_char_code = new hashmap <character, string> (); // coding code table map_code_char = new hashmap <string, character> (); // decoding code table} // coding is divided into four steps // 1. statistical Character Frequency // 2. generate the Huffman tree // 3. generate codec code table // 4. encode the public static string encode (string Str) {char [] cchar = Str. tochararray (); // 1. treemap <character, integer> map = new Treemap <character, integer> (); For (INT I = 0; I <cchar. length; I ++) {If (map. containskey (cchar [I]) {map. put (cchar [I], map. get (cchar [I]). intvalue () + 1);} else {map. put (cchar [I], 1) ;}// 2. generate the Huffman tree // generate the forest of the single-node tree by all characters first // then combine the single-node tree based on the priority into a tree queue <tree> forest = new priorityqueue <tree> (); set <map. entry <character, integer> set = map. entryset (); iterator <map. entry <character, integer> it = set. iterator (); While (it. hasnext () {// generate a single node tree map. entry <character, integer> en = it. next (); tree temp = new tree (); temp. root = new node (en. getkey (); temp. weight = en. getvalue (); Forest. add (temp);} while (forest. size ()> 1) {// merge a single-node tree into a tree T1 = forest. remove (); tree t2 = Forest. remove (); tree T3 = new tree (); t3.root = new node (); t3.weight = t1.weight + t2.weight; t3.root. leftchild = t1.root; t3.root. rightchild = T2.root; Forest. add (T3);} tree T = Forest. remove (); // the last tree // 3. mapstring code = ""; preorder (T. root, code, map_char_code, map_code_char); // 4. encoding string stringbuffer output = new stringbuffer (); For (INT I = 0; I <cchar. length; I ++) {output. append (map_char_code.get (cchar [I]);} return output. tostring () ;}// traverse the Huffman tree to generate the codec code table Private Static void preorder (node localroot, string code, Map <character, STR Ing> map_char_code, Map <string, character> map_code_char) {If (localroot! = NULL) {If (localroot. cchar! = '\ 0') {map_char_code.put (localroot. cchar, Code); map_code_char.put (Code, localroot. cchar);} preorder (localroot. leftchild, code + "0", map_char_code, map_code_char); preorder (localroot. rightchild, code + "1", map_char_code, map_code_char) ;}/// decodes // restores public static string decode (string Str) Information Based on the validation code table) {stringbuffer result = new stringbuffer (); stringbuffer sb = new stringbuffer (); For (INT I = 0; I <Str. le Ngth (); I ++) {sb. append (Str. charat (I); If (map_code_char.get (sb. tostring ())! = NULL) {result. append (map_code_char.get (sb. tostring (); sb = new stringbuffer () ;}} return result. tostring ();} public static void main (string [] ARGs) {string code = encode ("Susie says it is easy! "); System. out. println (CODE); string STR = decode (CODE); system. out. println (STR);} // ------------------------------------------------------------- public static string getstring () throws ioexception {inputstreamreader ISR = new inputstreamreader (system. in); bufferedreader BR = new bufferedreader (ISR); string S = BR. readline (); Return s ;}} // ================================================ ========================================================