zoukankan      html  css  js  c++  java
  • 数据结构 --- 二叉树(遍历)

    中序+后序转层序

    void levelorder(int post_root,int inL,int inR,int idx){
    	//边界:inL>inR 不要写成inL>=inR 
    	if(inL > inR) return ;
    	level.push_back({post[post_root],idx});
    	int k;
    	for(k = inL; k <= inR; k ++ ){
    		if(in[k] == post[post_root]) break;
    	}
    	levelorder(post_root - 1 - (inR - k),inL,k - 1,2 * idx);
    	levelorder(post_root - 1,k + 1,inR,2 * idx + 1);
    }
    
    bool cmp(Node a,Node b){
    	return a.idx < b.idx;
    }
    levelorder(n - 1,0,n - 1,1);
    sort(level.begin(),level.end(),cmp);
    

    中序+后序转先序

    void preorder(int post_root,int inL,int inR){
    	//边界:inL>inR 不要写成inL>=inR 
    	if(inL > inR) return ;
    	pre.push_back({post[post_root],idx});
    	int k;
    	for(k = inL; k <= inR; k ++ ){
    		if(in[k] == post[post_root]) break;
    	}
    	levelorder(post_root - 1 - (inR - k),inL,k - 1);
    	levelorder(post_root - 1,k + 1,inR);
    }
    preorder(n - 1,0,n - 1);
    sort(level.begin(),level.end(),cmp);
    

    1020 Tree Traversals (25分)

    #include<bits/stdc++.h>
    
    using namespace std;
    
    #define  mm(a,x) memset(a,x,sizeof a)
    #define  mk make_pair
    #define ll long long
    #define pii pair<int,int>
    #define inf 0x3f3f3f3f
    #define lowbit(x) (x) & (-x)
    #define endl "
    "
    
    const int N = 40;
    
    struct Node{
    	int data,idx;
    };
    
    int n;
    int in[N],post[N];
    vector<Node > level;
    
    /*
    中序:左根右
    后序:左右根
    
    层序:从根结点开始一层层遍历
     
    */
    
    void levelorder(int post_root,int inL,int inR,int idx){
    	//边界:inL>inR 不要写成inL>=inR 
    	if(inL > inR) return ;
    	level.push_back({post[post_root],idx});
    	int k;
    	for(k = inL; k <= inR; k ++ ){
    		if(in[k] == post[post_root]) break;
    	}
    	levelorder(post_root - 1 - (inR - k),inL,k - 1,2 * idx);
    	levelorder(post_root - 1,k + 1,inR,2 * idx + 1);
    }
    
    bool cmp(Node a,Node b){
    	return a.idx < b.idx;
    }
    int main() {
    	cin >> n;
    	for(int i = 0; i < n; i ++ ) cin >> post[i];
    	for(int i = 0; i < n; i ++ ) cin >> in[i];
    	levelorder(n - 1,0,n - 1,1);
    	sort(level.begin(),level.end(),cmp);
    	for(int i = 0; i < n; i ++ ){
    		if(i) cout<<" ";
    		cout<<level[i].data;
    	}
    	return 0;
    }
    
  • 相关阅读:
    迭代器模式(Iterator)
    原型模式(Prototype)
    生成器模式(Builder)
    策略模式(Strategy)
    访问者模式(Visitor)
    桥接模式(Bridge)
    命令模式(Command)
    工厂方法模式(Factory Method)
    解决在Win7下安装MyGeneration,不能使用的问题
    Nhibernate拒绝配置文件(NHibernate.Mapping.Attributes的使用)
  • 原文地址:https://www.cnblogs.com/bingers/p/14044282.html
Copyright © 2011-2022 走看看