/*************************************** * Time: June 23, 2017 * AUTHOR:LCY * content: Two hierarchical traversal of a fork tree * need to use the data structure of the queue, Direct import is available * 1. First put the root node in the queue. 2. When the queue is non-empty, loop through step 3 to step 5, otherwise execute 6; 3. Get a node from the queue, access the node, 4. If the left subtree of the node is non-null, the left subtree of the node is in the queue; if the right subtree of the node is not empty, the right subtree of the node is enqueued column; 6. End. ***************************************/ ImportJava.util.ArrayDeque; ImportJava.util.Queue; Public classBintree {Private Chardate; PrivateBintree Lchild;//left child PrivateBintree Rchild;//Right Child PrivateBintree (Charc) {Date=C; } Public Static voidBfsorder (Bintree T) {if(t==NULL)return ; Queue<BinTree> queue =NewArraydeque<bintree>(); //Queue tip: Using offer and poll is better than add and remove in that their return value can be judged by success or not, without throwing an exceptionQueue.offer (T); //algorithm 1: root node enters queue while(!queue.isempty ())//Algorithm 2: If the queue is not empty, loop through step 3-5, otherwise perform step 6{T=queue.poll ();//algorithm 3: Send a node out of the queue and access the nodeSystem.out.print (t.date); if(t.lchild!=NULL)//Algorithm 4: If the left sub-tree of the node is non-null, the node's left child node is queued;Queue.offer (T.lchild); if(t.rchild!=NULL)//Algorithm 5: If the left subtree of the node is non-null, the node's right child node is placed in the queue;Queue.offer (T.rchild); } //End of Step 6 } Public Static voidMain (string[] args) {Bintree B1=NewBintree (' a '); Bintree B2=NewBintree (' B '); Bintree B3=NewBintree (' C '); Bintree B4=NewBintree (' d '); Bintree b5=NewBintree (' e '); Bintree b6=NewBintree (' F '); Bintree B7=NewBintree (' G '); /*** A */* b c */\/* d E F g*/B1.lchild=B2; B1.rchild=B3; B2.lchild=b4; B2.rchild=b5; B3.lchild=b6; B3.rchild=B7; System.out.println (12121); Bintree.bfsorder (B1); System.out.println (); }}
Test results
Graduated.-java Two-fork tree hierarchy traversal algorithm