A sequence of sequential and sequential traversal sequences of two-forked trees is given, and the sequence of the two-forked tree is obtained.
In order traversal, the first must be the root node, and then the next node in the first order traversal is on the left or right side of the root node in the middle sequence traversal, the left node is in the left subtree of the root junction, and the right is in the right subtree. Depending on which side of the root junction the node looks for on that side, if there is no node on that side, add the node to it, or continue looking for the root node with that node until you build a complete binary tree. Finally, the output binary tree is traversed by post-post.
Code:
#include <cstdio> #include <cstring> #include <iostream> using namespace std;
struct node{int num;
Node *l,*r;
node (int x): num (x), L (null), R (null) {}};
int n;
int dlr[1005],ldr[1005];
void Insert (node *h,int x) {bool flag=0;
for (int i=0;i<n;i++) {if (ldr[i]==h->num) flag=1;
if (ldr[i]==x) break;
} if (!flag) {if (h->l==null) {Node *n=new node (x);
h->l=n;
Return
} else Insert (H->L,X);
} else {if (h->r==null) {Node *n=new node (x);
h->r=n;
Return
} else Insert (H->R,X);
}} void Postorder (node *h) {if (h->l!=null) postorder (h->l);
if (h->r!=null) postorder (h->r); printf ("%d%s", H->num, ((--n) ==0)? "
\ n ":");}
int main () {//freopen ("In.txt", "R", stdin);
while (Cin>>n) {for (int i=0;i<n;i++) cin>>dlr[i]; for (int i=0;i<n;i++) cin>>ldr[i];
Node h (dlr[0]);
for (int i=1;i<n;i++) {insert (&h,dlr[i]);
} postorder (&h);
} return 0;
}