Given a tree-shaped structure,
Convert it to child parent notation:
The following is a Java implementation://first-order traversal
Importjava.util.ArrayList; Public classtreetraverse{Static int[] Father = { 0,1,1,1,2,2,2,6,6,6,8,4,4,12,13,13,13 }; Static int[] Child = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17 }; Public Static voidMain (string[] arg) {ArrayList<Tree> trees =NewArraylist<>(); Trees.add (NewTree (0)); intLen =child.length; for(inti = 0; I! = Len; i + +) {Trees.add (NewTree (Child[i]); } for(inti = 0; I! = Len; i + +) {Tree _father=Trees.get (Father[i]); if(_father.getfchild () = =NULL) {_father.setfchild (Trees.get (child[i)); System.out.println ("Father for" + father[i "+" big child for "+Child[i]); Continue; } Tree sibiling=_father.getfchild (); while(sibiling.getchildsibling ()! =NULL) {sibiling=sibiling.getchildsibling (); } sibiling.setchildsibling (Trees.get (Child[i])); System.out.println ("Child for" + sibiling.getnum () + "right brother for" +Child[i]); } Traverse (Trees.get (0)); } Static voidTraverse (Tree father) {if(Father.getfchild () = =NULL){ return; } System.out.print (Father.getfchild (). Getnum ()+ " "); Traverse (Father.getfchild ()); Tree sibiling=Father.getfchild (); while(sibiling.getchildsibling ()! =NULL) {sibiling=sibiling.getchildsibling (); System.out.print (Sibiling.getnum ()+ " "); Traverse (sibiling); } } Static classtree{Private intnum; PrivateTree Fchild; PrivateTree childsibling; PublicTree (intnum) { Super(); This. num =num; } Public intGetnum () {returnnum; } Public voidSetnum (intnum) { This. num =num; } PublicTree Getfchild () {returnFchild; } Public voidsetfchild (Tree fchild) { This. Fchild =Fchild; } PublicTree getchildsibling () {returnchildsibling; } Public voidsetchildsibling (Tree sibling) { This. childsibling =sibling; } }}
The output is:
Tree traversal (Java)---child parental representation