IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [PAT 1086]二叉树(前序遍历+中序遍历)建树并得到(后序遍历)

    izzxaz发表于 2016-07-13 07:39:00
    love 0
    #include<iostream>
    #include<algorithm>
    #include<string>
    #include<stack>
    using namespace std;
    
    typedef struct TreeNode {
    	int data;
    	struct TreeNode *left,*right;
    } TreeNode;
    
    TreeNode *pTree = new TreeNode;
    
    int n,b=0,b2=0,p,op=0;
    
    stack<int> s;
    
    int arr_pre[40],arr_mid[40],r[40],h=0;
    
    void last_order(TreeNode * Tree){
    	if(Tree!=NULL){
    		last_order(Tree->left);
    		last_order(Tree->right);
    		r[h++]=Tree->data;
    	}
    	return;
    }
    void Build_Tree(TreeNode* &Tree,int p1/* 中序遍历扫描起点 */,int p2 /* 中序遍历扫描终点 */){
    	if(p1>p2) return;
    	Tree = new TreeNode;
    	Tree->left = Tree->right = NULL;
    	int pos;
    	for(int i=p1;i<=p2;i++){
    		if(arr_mid[i]==arr_pre[op]) {
    			pos=i;
    			break;
    		}
    	}
    	Tree->data=arr_pre[op++];
    	Build_Tree(Tree->left,p1,pos-1);
    	Build_Tree(Tree->right,pos+1,p2);
    	//cout<<Tree->data<<"| "; 
    	return;
    }
    
    int main(){
    	string act;
    	cin>>n;
    	pTree->left=pTree->right=NULL;
    	while(cin>>act){
    		if(act=="Push"){
    			cin>>p;
    			s.push(p);
    			arr_pre[b++]=p; 
    		}
    		if(act=="Pop"){
    			arr_mid[b2++]=s.top();
    			s.pop();
    		}
    	}
    
    	Build_Tree(pTree,0,n-1);
    	last_order(pTree);
    	for(int i=0;i<h-1;i++) cout<< r[i] <<" ";
    	cout<<r[h-1]<<endl;
    	return 0;
    }
    

    9 total views, 9 views today



沪ICP备19023445号-2号
友情链接