zoukankan      html  css  js  c++  java
  • 由后序遍历与中序遍历确定前序遍历

    #include<iostream>
    #include<string>
    using namespace std;
    
    struct Node
    {
        Node * lchild;
        Node * rchild;
        char c;
    };
    
    Node* build(string in ,string pos)
    {
    	Node* t=NULL;
    	if(in.size()>0)
    	{
    		t=new Node();
    		t->c=pos[pos.length()-1];
    		t->lchild=NULL;
    		t->rchild=NULL;
    	}
    	if(in.size()>1)
    	{
    		int root=0;
    		for(int i=0;i<in.size();i++)
    			if(in[i]==t->c)
    				{
    					root=i;
                        break;
    				}
    		string pos_left = pos.substr(0, root);
    		string in_left = in.substr(0,root);
    		t->lchild=build(in_left, pos_left);
    
    		string pos_right = pos.substr(root, pos.length()-1-root);
    		string in_right = in.substr(root+1, in.size()-root-1);
    		t->rchild=build(in_right, pos_right);
    	}
    	return t;
    }
    
    void PreOrder(Node* t)
    {
    	cout<<t->c;
    	if(t->lchild)PreOrder(t->lchild);
    	if(t->rchild)PreOrder(t->rchild);
    }
    
    int main()
    {
        string in, pos;
        cin>>in>>pos;
        Node* t= build(in, pos);
        PreOrder(t);
         
        cout<<endl;
    
        return 0;
    }
    

      

  • 相关阅读:
    115. Distinct Subsequences
    91. Decode Ways
    72. Edit Distance
    python 输出 a+b
    求次小生成树
    判断最小生成树是否唯一
    二分法求最优值
    黑科技
    线段树+ 区间更新
    2018ICPC青岛赛区J题
  • 原文地址:https://www.cnblogs.com/KennyRom/p/6168398.html
Copyright © 2011-2022 走看看