Title: Re-Restoring a two-fork tree based on First order traversal and middle sequence traversal
Ideas:
1. Find the first number in the first order and assign it to the root node root->data;
2. Find the first number in the ordinal sequence;
3. The sequence to the left of the middle sequence is the root node Zuozi (left recursion), and the right side of the sequence is root (right recursion).
The code is as follows:
#include <iostream>using namespacestd;structtreenode{intdata; Treenode*Lchild; Treenode*rchild;};//Rebuilding a binary tree: recursive constructionTreenode *build (int*first,int*second,intlength) { //determine if the parameters are legitimate if(first==null| | second==null| | length<=0) returnNULL; introotvalue=first[0]; Treenode*root=NewTreenode (); Root->data=Rootvalue; Root->lchild=root->rchild=NULL; //only one node is returned. if(length==1) { if(first[0]==second[0]) returnRoot; Else Throwexception"input error!");//throws an exception, in C # is the throw new Exception (); } //recursive at multiple nodes. Else { intI=0; //finding the root node in the middle sequence traversal while(i<length&&second[i]!=rootvalue) I++; if(i==length)Throwexception"input error!!"); //recursive left sub-tree, I left sequence if(i>0) {root->lchild=build (first+1, Second,i); } //Recursive right sub-tree, I right-hand sequence if(i<length-1) {root->rchild=build (first+i+1, second+i+1, length-i-1); } } returnRoot;}//Print binary tree by middle ordervoidPrint (Treenode *root) { if(root) {print (Root-lchild); cout<<root->data<<Endl; Print (Root-rchild); }}intMain () {Try { inta[Ten]={1,2,4,7,3,5,6,8}; intb[Ten]={4,7,2,1,5,3,8,7}; Treenode*root=build (A, B,8); print (root); } Catch(ConstException &e) {Cerr<<e.what () <<endl;//Cerr used to output exceptions }}
Test results:
Rebuilding a binary tree