3 Importjava.util.LinkedList;4 Importjava.util.List;5 ImportJava.util.concurrent.BlockingDeque;7 ImportTree. Bitreetraverse.node;8 9 /**Ten * Three kinds of traversal of binary tree: One * First order traversal, middle sequence traversal, subsequent traversal A * @authorAdministrator - * 1 - * / the * 2 3 - * / \ / - * 4 5 6 7 - * / + * 8 9 - * Binary tree is an ordered tree with a maximum of two child nodes per node + * First Order traversal: Right subtree ----left dial hand tree 1,2,4,8,9,5,3,6,7 A * Middle sequence traversal: Left dial hand tree ------right subtree 8,4,9,2,5,1,6,3,7 at * Subsequent traversal: Left dial hand tree, right subtree, root 8,9,4,5,2,6,7,3,1 - * - * - */ - Public classBitreetraverse { - Private int[] Array = {1,2,3,4,5,6,7,8,9}; in Private StaticList<node> nodeList =NULL; - Public Static classnode{ to Node leftchild; + Node rightchild; - intdata; the PublicNode (intNewData) { *data =NewData; $Leftchild =NULL;Panax NotoginsengRightchild =NULL; - } the } + Public voidCreatebitree () { ANodeList =NewLinkedlist<node>(); the for(intNodeindex = 0; Nodeindex < Array.Length; nodeindex++) { +Nodelist.add (NewNode (Array[nodeindex])); - } $ for(intParentindex = 0; Parentindex < array.length/2-1; parentindex++) { $Nodelist.get (parentindex). Leftchild = Nodelist.get (parentindex*2+1); -Nodelist.get (parentindex). Rightchild = Nodelist.get (parentindex*2+2); - } the intLastparentindex = array.length/2-1; -Nodelist.get (lastparentindex). Leftchild = Nodelist.get (lastparentindex*2+1);Wuyi if(array.length%2==1) { theNodelist.get (lastparentindex). Rightchild = Nodelist.get (lastparentindex*2+2); - } Wu } - /** About * First Order traversal $ * @paramnode - */ - Public Static voidPreordertraverse (node node) { - if(node = =NULL) { A return ; + } theSystem.out.print (node.data+ ","); - Preordertraverse (node.leftchild); $ Preordertraverse (node.rightchild); the } the Public Static voidInordertraverse (node node) { the if(node = =NULL) { the return ; - } in the Inordertraverse (node.leftchild); theSystem.out.print (node.data+ ","); About Inordertraverse (node.rightchild); the } the Public Static voidPostordertraverse (node node) { the if(node = =NULL) { + return ; - } the Bayi Postordertraverse (node.leftchild); the the Postordertraverse (node.rightchild); -System.out.print (node.data+ ","); - } the Public Static voidMain (string[] args) { theBitreetraverse Bitree =Newbitreetraverse (); the Bitree.createbitree (); theNode root = Nodelist.get (0); -System.out.println ("First-order Traversal"); the Preordertraverse (root); the System.out.println (); theSystem.out.println ("Middle sequence traversal");94 Inordertraverse (root); the System.out.println (); theSystem.out.println ("Post-traversal"); the Postordertraverse (root);98 } About -}
Algorithm of binary Tree