Because of the presence of pointers in C + +, you can make the pointer of the two-fork tree node as the actual parameter of the insertion function, in the function body through the * operation to the real node pointer, the node left child pointer, the node right child pointer changes, so it is easy to use recursion to transform the tree problem into a small tree problem. However, in Java, because there is no pointer only reference, if you need to implement recursive two-tree element insertion, the node needs to be wrapped, and because the recursive need to recursive tree problems to the subtree, the wrapper class node needs to be changed, but because the last need is the root node, so the root node needs to be backed up, after the completion of the recursive Here is the implementation code:
1 Packagetest;2 3 4 5 Public classbitree{6 7 Public Static voidMain (string[] args) {8Bitree B =NewBitree ();9 b.operate ();Ten } One Public voidoperate () { A int[] num = {2,3,4,1,5}; - intLen =num.length; - //System.out.println (len); theTree T =NewTree (); - for(inti=0; i<len; i++){ - Insert (T,num[i]); - } + //System.out.println (t.root.val); - //System.out.println (t.root.right.val); + //System.out.println (t.root.left.val); A Traverse (t.root); at - } - - Public voidInsert (Tree t,inte) { -BNode temp =NewBNode (e); -BNode backUp =T.root; in if(T.root = =NULL){ -T.root =temp; to}Else{ + if(E = =t.root.val) { - return; the}Else if(e<t.root.val) { *T.root =Backup.left; $ Insert (t, e);Panax NotoginsengBackup.left =T.root; -T.root =backUp; the +}Else{ AT.root =Backup.right; the Insert (t,e); +Backup.right =T.root; -T.root =backUp; $ } $ } - } - Public voidTraverse (BNode t) { the if(T = =NULL){ - return;Wuyi } the System.out.println (t.val); - Traverse (t.left); Wu Traverse (t.right); - About } $ - } - - classbnode{ A Public intVal; + PublicBNode left; the PublicBNode right; - PublicBNode (intval) { $ This. val =Val; theleft =NULL; theright =NULL; the } the } - in classtree{ the PublicBNode Root; the PublicTree () { AboutRoot =NULL; the } the}
Two recursive insertion of a fork tree "Java implementation"