Binary Tree--construction of two-fork tree based on traversal

Source: Internet
Author: User

The three kinds of traversal methods in binary tree are the most well-known, we can only determine a binary tree by the First order traversal, the middle sequence traversal, or the sequential traverse + post-order traversal. But notice that the first sequence traversal + post-order traversal cannot determine a binary tree, But if a binary tree has only a node with a degree of 0 and a degree of 2, this traversal can also determine a certain two-fork tree.

First Order + middle order –> Structure two fork Tree

Let's take a look at the following separately, according to the order of the first Order + sequence traversal, how to restore a binary tree, the code is as follows:

//First in a recursive way PublicTreeNodeBuildtree(int[] Preorder,int[] inorder) {returnBuildtree (Preorder,0, Inorder, Inorder.length-1,0);}PrivateTreeNodeBuildtree(int[] Preorder,intIdxint[] inorder,intEndintStart) {if(idx >= preorder.length | | Start > End) {return NULL; } TreeNode root =NewTreeNode (Preorder[idx]);intI//Find root node,         for(i = end; I >= start; i--) {if(Preorder[idx] = = Inorder[i]) { Break; }        }//In ordinal group, Zuozi set [Start, I-1]Root.left = Buildtree (preorder, IDX +1, Inorder, I-1, start);//In ordinal group, right subtree set [I+1, end], note that the index,idx of the first order queue is the location of the root node, then the right subtree can only be on the right side of the IDX, until end, but the value of the first order index is idx+i-start+1, Because of the Saoto (I-start) elements of the sequence segment above, plus the root node, the start position of the right subtree below the sequence traversal is idx+i-start+1 (note this section).Root.right = Buildtree (preorder, idx + I-start +1, Inorder, End, i+1);returnRoot }

The root node is the first node of the sequence traversal, finds the corresponding position of the node in the sequential table, divides the sequence table into two, and classifies the relationship of the left and right sub-trees of the first sequence table according to the dividing relation of the sub-tree of the sequence table, and then goes on.

//Non-recursive way PublicTreeNode Buildtree (int[] Preorder,int[] inorder) {intlen = preorder.length;//Same length        if(preorder==null| | Len = =0){returnNull } treenode[]Stack=NewTreenode[len]; boolean[] Flag =NewBoolean[len];intk=-1, unsee=-1; for(inti =0, j =0; I < len| | J<len;) {if(k<0) {k++;Stack[K] =NewTreeNode (Preorder[i]); FLAG[K] =false;                unsee++;            i++; }Else{if(unsee>=0&AMP;&AMP;INORDER[J] = =Stack[Unsee].val) { for(intx = Unsee; x < K; X + +) {if(X==unsee) {Stack[X].left =Stack[x+1]; }Else{Stack[X].right =Stack[x+1];                    }} k = Unsee; Flag[unsee] =true; j + +; while(unsee>=0&&flag[unsee]==true) {unsee--; }                }Else{k++;Stack[K] =NewTreeNode (Preorder[i]); FLAG[K] =false;                    Unsee = k;                i++; }            }        } for(inti =0; i<k; i++) {Stack[I].right =Stack[i+1]; }return Stack[0]; }
Middle order + Post –> construction two fork Tree

Recursive way:

map<integer,integer> map =NewHashmap<> (); PublicTreeNodeBuildtree(int[] inorder,int[] postorder) {if(Inorder = =NULL|| Inorder.length = =0)return NULL; for(inti =0;    i< inorder.length;i++) {map.put (inorder[i],i); }returnDFS (Inorder,0, Inorder.length,postorder,0, postorder.length-1);}PrivateTreeNodeDFS(int[] inorder,intIstartintIend,int[] Postorder,intPstart,intPend) {if(Pstart > Pend)return NULL; TreeNode root =NewTreeNode (Postorder[pend]);intIMiD = map.Get(Root.val);//post-traversal of the tail node is the root nodeRoot.left = DFS (inorder,istart,imid-1, Postorder,pstart,pstart + imid-istart-1);//Use the Sequence traversal list, find the two fork tree in the left and right sub-tree segmentation point, determine the length of the left and right sub-tree, and then use this length to the post-order Traversal list segmentation (the overall structure of the order is left----> R---->), once, you can get the lastRoot.right = DFS (inorder,imid+1, Iend,postorder,pstart + imid-istart,pend-1);returnRoot }

In this program, in contrast to the first Order + middle order , the HashMap method is used to obtain the index of the corresponding value in the sequence table, both of which are better understood; the specific recursive thought is similar to the above, not repeating.

Non-recursive mode

 PublicTreeNodeBuildtree(int[] inorder,int[] postorder) {intI=0;intj=0; TreeNode root=NULL; while(I<inorder.length && j<postorder.length) {if(Inorder[i]==postorder[j]) {TreeNode node =NewTreeNode (Inorder[i]);            Node.left=root;            root = node;            i++;        j + +; }Else{TreeNode node =NewTreeNode (Inorder[i]);            Node.left=root; root = node;intK=j; while(Postorder[k]!=inorder[i])            {k++; }int[] ia = Arrays.copyofrange (inorder, i+1, i+1+K-J);int[] pa = Arrays.copyofrange (Postorder, J, K);            node = Buildtree (IA, PA);            Root.right=node; i=k+1; j=k+1; }    }returnRoot;}
About recursion

In binary tree operation, the use of recursion is very common, recursive code is very concise, but also easier to understand, but recursive this idea of the most system stack requirements is very high, when the amount of data is larger, it may be easy to stack overflow, so it is necessary to rewrite the recursive program into a non-recursive program, Although the non-recursive program is more complicated, the code quantity is large, but it is universal.

Binary Tree--construction of two-fork tree based on traversal

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.