Problem Description:
Input shows the middle sequence traversal non-recursive, stack operation, output tree post-order traversal
Key Issues
The order of the push is a sequential traversal, and the Order of the POPs is the middle sequence traversal
Problems are converted to sequential traversal and middle order traversal for subsequent traversal
/*=============================================================================# COPYRIGHT NOTICE# Copyrig HT (c) 2015## @Author: tonychou# @Email: [Email protected]# @Filename:/home/zhoud axia/program/pat_mooc_ds\03_3.cc# @Last modified:2015-06-30 21:22# @Description: ================= ============================================================*/#include <iostream>#include <stack>#include <vector>#include <string>#include <stdio.h>using namespace STD;intFind_head ( vector<int>&v,intData) { for(inti =0; I!= v.size (); ++i)if(V[i]==data)returni;}voidFind_post ( vector<int>&V1, vector<int>&v2,intLEFT2,intRight2,intHEAD1) {intHead2 = Find_head (v2, v1[head1]);intLeft_size = head2-left2;if(Head1!=v1.size ()) {if(head2>left2) Find_post (v1,v2,left2, head2-1, head1+1);if(head2<right2) Find_post (v1,v2,head2+1, right2,head1+left_size+1);if(head1==0)cout<< V1[head1];Else cout<< V1[head1] <<" "; }}intMain () {intNstringSintNode vector<int>Pre_v; vector<int>In_v; Stack<int>StaCin>> N; for(intI=0; I! =2*n; ++i) {Cin>> s;if(s=="Push"){Cin>>node; Pre_v.push_back (node); Sta.push (node); }Else{In_v.push_back (Sta.top ()); Sta.pop (); }} find_post (Pre_v,in_v,0, Pre_v.size ()-1,0);return 0;}
Analytical
First Order traversal in V1
1 2 3 4 5 6
Post-post traversal
3 2 4 1 6 5
The parameters in recursion "left2 right2" are Zuozi in the V2 range, Head1 is the position of the head node in V1
Head2 is the position of the head node in v2
The exit of the recursion is the head1 traversing to the V1 tail,
When head2! =left2 time recursion [left2,head2-1]
Head2! = right2 when recursive [head2+1,right2]
Otherwise output V1[HEAD1]
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
03-Tree 3. Tree traversals Again (25)