Title: The pre-sequence traversal and the middle sequence traversal of a given binary tree, generating a two-fork tree.
Example:
Pre-sequence traversal array: prearr[]:{1,2,4,5,3,6,7}
Middle Sequence Traversal array: inarr[]:{4,2,5,1,6,3,7}
The resulting two fork tree is as follows:
Problem Solving Ideas:
By the nature of the pre-order variables of the two-fork tree: Prearr[0] is the root of the array, there is a binary tree according to the nature of the sequence traversal, {4,2,5} is a two-tree left subtree, {6,3,7} on the right subtree, repeat the operation of the two-tree
Public classSolution { PublicTreeNode Reconstructbinarytree (int[] Pre,int[] in) {TreeNode root=NewTreeNode (Pre[0]);//the first number of the preamble is determined to be the root intLen =pre.length; //when there's only one number if(len = = 1) {Root.left=NULL; Root.right=NULL; returnRoot; } //find the root position in the middle order intRootval =Root.val; inti; for(i = 0; i < Len; i++) { if(Rootval = =In[i]) Break; } //Create a left sub-tree if(I > 0) { int[] PR =New int[i]; int[] ino =New int[i]; for(intj = 0; J < I; J + +) {Pr[j]= Pre[j + 1]; } for(intj = 0; J < I; J + +) {Ino[j]=In[j]; } root.left=reconstructbinarytree (PR, INO); } Else{root.left=NULL; } //Create right subtree if(Len-i-1 > 0) { int[] PR =New int[Len-i-1]; int[] ino =New int[Len-i-1]; for(intj = i + 1; J < Len; J + +) {ino[j-I-1] =In[j]; Pr[j-I-1] =Pre[j]; } root.right=reconstructbinarytree (PR, INO); } Else{root.right=NULL; } returnRoot; } Public Static voidMain (string[] args) {int[] Prearr = {1, 2, 4, 5, 3, 6, 7}; int[] Inarr = {4, 2, 5, 1, 6, 3, 7}; Solution S=Newsolution (); TreeNode Root=S.reconstructbinarytree (Prearr, Inarr); S.postorder (root); }
Binary tree generation of two-fork tree based on the first ordinal group of binary tree and the sequence traversal array