Binary tree is a special tree structure, each node has a maximum of two sub-nodes, each of the two nodes have left and right points, the order can not be reversed. Recursive definitions are generally used to define binary trees, so problems related to two-tree can be solved by recursion. Next, we introduce a method of constructing two-fork tree based on a known two-fork tree structure. The structure of two binary trees is given first, as shown in:
1) based on the existing two-fork tree structure, a node array is generated, and a two-fork tree is constructed based on the node array. A positive number that is entered by the contract indicates its node numbers, and negative numbers indicate that the node does not exist. From the root node, construct its left subtree, and if there is a left dial hand tree on the tree, continue until there is no left subtree, and then construct the right sub-tree. Taking a as an example to illustrate the process of generating an array of nodes, set the node array as Nodearr. First access root node 1 (nodearr=[1]), with left dial hand tree and root node is 2 (nodearr=[1,2]), 2 for the root node continues to access, there is still left dial hand tree and the root node is 4 (nodearr=[1,2,4]), continue to access, no Zuozi (nodearr=[ 1,2,4,-1]), there is no right subtree (nodearr=[1,2,4,-1,-1]), return to the upper layer, Access 2 right subtree, and right child tree root node is 5 (nodearr=[1,2,4,-1,-1,5]), found that 5 has no left node and right node (Nodearr =[1,2,4,-1,-1,5,-1,-1]), and so on, the node array of end A is nodearr=[1,2,4,-1,-1,5,-1,-1,3,-1,6,-1,-1]. Similarly, a node array of B is nodeArr2, with Nodearr2=[1,2,4,-1,-1,5,9,-1,-1,-1,3,6,7,-1,8,-1,-1,-1,-1].
2) based on the node array, generate a two-fork tree with the following code:
1 Public classTraversal {2 Static intStep=0;3 Public Static voidMain (string[] args) {4 int[] nodearray=New int[]{1,2,4,-1,-1,5,-1,-1,3,-1,6,-1,-1};5 int[] nodearray2=New int[]{1,2,4,-1,-1,5,9,-1,-1,-1,3,6,7,-1,8,-1,-1,-1,-1};6Node root=NewNode ();7root=Createbinarytree (root,nodearray2);8System.out.println ("End");9 }Ten Public StaticNode Createbinarytree (node root,int[] nodearray) { One intVal=-1; A Try { -val =Nodearray[step]; -step++; the } - Catch(ArrayIndexOutOfBoundsException ex) { -System.out.println ("Arrayindexoutofbounds,check The Nodearray"); - } + if(val<0){ -System.out.println ("leaf node")); +root=NULL; A returnRoot; at } -root=NewNode (Val);///point to New Object - //step++; -Root.leftnode=Createbinarytree (root.leftnode,nodearray); -Root.rightnode=Createbinarytree (root.rightnode,nodearray); - returnRoot; in } - } to classnode{ + Public intValue=-1; - PublicNode Leftnode; the PublicNode Rightnode; * PublicNode (intval) { $Value=Val;Panax Notoginseng } - PublicNode () { the } +}
View Code
3) the results are as follows:
Construct a two-fork tree