Idea: Similar to hierarchical traversal, implemented with queues. Each layer node into the queue, the end of adding 1, and then out of the queue, while adding nodes of the node into the queue, encountered-1 depth plus 1;
Java code:
1 Packagetest;2 Importjava.util.ArrayList;3 ImportJava.util.Iterator;4 Importjava.util.LinkedList;5 ImportJava.util.Queue;6 ImportJava.util.Scanner;7 classnode{8 9 PublicNode (intFatherintChild ) {Ten This. Father =father; One This. Child =Child ; A } - intfather; - intChild ; the } - - Public classTree { - /**** + * Hierarchical traversal of the idea, queue implementation, by layer added to the queue, at the end of the Enqueue-1; - */ + Public Static intDeepintN,arraylist<node>tree) { A intCount=0; at intj=0;//record how many nodes were manipulated; - if(n<=0){ - return0; -}Else if(n==1){ - return2; -}Else{ inQueue<integer> queue=NewLinkedlist<integer>(); -Queue.offer (0); toJ + +; +Queue.offer (-1);// - Booleanflag=false;//determine whether to the tail node; the while(!Queue.isempty ()) { * //Printdata (queue); $Integer Data=Queue.poll ();Panax Notoginseng //System.out.println (); - //System.out.println ("Data:" +data); the //System.out.println (); + if(j==n&&flag==false){ AQueue.offer (-1); theflag=true; +}Else if(Data==-1){ - if(flag) { $count++; $}Else{ -Queue.offer (-1); -count++; the } -}Else{Wuyi for(inti = 0;i < Tree.size (); i + +){ the if(Tree.get (i). father==data) { - Queue.offer (Tree.get (i). Child); WuJ + +; - } About } $ } - } - - } A + returncount; the } - Public Static voidPrintdata (queue<integer>queue) { $ for(Iterator it2 =queue.iterator (); It2.hasnext ();) { theSystem.out.println ("Q:" +It2.next ()); the } the } the - Public Static voidMain (string[] args) { in //TODO auto-generated Method Stub theScanner in =NewScanner (system.in); the //While (In.hasnext ()) { About intn=in.nextint (); theArraylist<node> tree =NewArraylist<node>(); the for(inti=0;i<n-1;i++){ the intFather=in.nextint (); + intChild=in.nextint (); -Node node=NewNode (father,child); the tree.add (node); }Bayi System.out.println (Deep (N,tree)); the // } the } - - } the /** the * the * the 9 - 0 1 the 0 2 the 1 3 the 1 494 2 5 the 2 6 the 3 7 the 3 898 About 5 - 0 1101 0 2102 1 3103 1 4104 **/
Operation Result:
Ten to 84
There is no AC in the race Code network, we can try.
"Meet Time" millet written test-height of the tree-java